IT常识
技术 Python PHP JavaScript IOS Android Java 数据库 资源 公众号 代码片段 github
  • IT常识
  • web服务器

[LeetCode]233 Number of Digit One(数位DP)

Posted 2020-09-03 tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]233 Number of Digit One(数位DP)相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/number-of-digit-one/?tab=Description

题意:求[1,n]内1的个数。

裸数位DP,好久不写都快不会写了。。这么水

 1 class Solution {
 2 public:
 3     int dp[30][30];
 4     int digit[30];
 5 
 6     int dfs(int l, int cnt, bool flag) {
 7         if(l == 0) return cnt;
 8         if(!flag && ~dp[l][cnt]) return dp[l][cnt];
 9         int pos = flag ? digit[l] : 9;
10         int ret = 0;
11         for(int i = 0; i <= pos; i++) {
12             ret += dfs(l-1, cnt+(i==1), flag&&(pos==i));
13         }
14         if(!flag) dp[l][cnt] = ret;
15         return ret;
16     }
17 
18     int countDigitOne(int n) {
19         memset(dp, -1, sizeof(dp));
20         int pos = 0;
21         while(n) {
22             digit[++pos] = n % 10;
23             n /= 10;
24         }
25         return dfs(pos, 0, true);
26     }
27 };

 

以上是关于[LeetCode]233 Number of Digit One(数位DP)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 233. Number of Digit One

LeetCode 233. Number of Digit One

LeetCode-233 Number of Digit One

[LeetCode]233 Number of Digit One(数位DP)

Leetcode 233 Number of Digit One

233 Number of Digit One 数字1的个数

(c)2006-2024 SYSTEM All Rights Reserved IT常识