思路:就是数位dp,dp[idx][sum][limit]代表,到idx位,前面有sum个0,有没有limit限制;
class Solution {
public:int dp[20][50][2];int len; int pos[20];int countDigitOne(int n) {for(int i=0;i<15;i++)for(int k=0;k<50;k++) for(int j=0;j<=1;j++)dp[i][k][j]=-1;return work(n);}int work(int n){len=0;while(n){pos[++len]=n%10;n/=10;}return dfs(len,0,1);}int dfs(int idx,int sum,int limit){if(idx<=0){return sum;}if(dp[idx][sum][limit]!=-1) return dp[idx][sum][limit];int ans=0;int end;if(limit) end=pos[idx];else end=9;for(int i=0;i<=end;i++){if(i==1) {ans+=dfs(idx-1,sum+1,limit&&(i==pos[idx]));}else ans+=dfs(idx-1,sum,limit&&(i==pos[idx]));}return dp[idx][sum][limit]=ans;}
};