首页 > 代码库 > LeetCode 233. Number of Digit One

LeetCode 233. Number of Digit One

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