LeetCode 233. Number of Digit One
阿新 • • 發佈:2017-07-14
tdi pan follow return number mil sta etc family
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
For example:
Given n = 13,
Return 6, because digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
本來想湊一個關於階乘的題目,做個筆記,不枉我昨天A八個小時才A掉的一道題,結果發現一道數位dp,順便來復習一下。
記憶化搜索的數位dp方法
status表示某個數的1的個數
class Solution { public: int dp[12][12]; int a[12]; int dfs(int pos, int status, bool limit) { if(pos == 0) return status; if(!limit && dp[pos][status] != -1) return dp[pos][status]; int up = limit ? a[pos] : 9; int ans = 0; for(int i = 0; i <= up; i++) { int nstatus = status; if(i == 1) nstatus++; ans += dfs(pos-1, nstatus, limit && up == i); } if(!limit) dp[pos][status] = ans; return ans; } int countDigitOne(int n) { int len = 0, nn = n;if(n<=0) return 0; while(n) { a[++len] = n % 10; n /= 10; } a[len + 1] = 0; memset(dp, -1, sizeof(dp)); return dfs(len, 0, true); } };
LeetCode 233. Number of Digit One