动态规划-数位dp-233. 数字 1 的个数

2020-04-13 11:38:31

问题描述:

给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。

示例:

输入: 13
输出: 6 
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。

问题求解:

可以使用数位dp进行高效求解。

dp[pos][cnt] : 处理到当前数位之前一共出现了cnt个1,总共能得到的1的数量。

    int[] digits = new int[64];
    int[][] dp = new int[64][64];
    
    public int countDigitOne(int n) {
        if (n <= 0) return 0;  
        int pos = 0;
        while (n > 0) {
            digits[pos++] = n % 10;
            n /= 10;
        }
        return dfs(pos - 1, 0, true);
    }
    
    public int dfs(int pos, int cnt, boolean limit) {
        if (pos == -1) return cnt;
        if (!limit && dp[pos][cnt] != 0) return dp[pos][cnt];
        int up = limit ? digits[pos] : 9;
        int res = 0;
        for (int i = 0; i <= up; i++) {
            res += dfs(pos - 1, cnt + (i == 1 ? 1 : 0), limit && i == up);
        }
        if (!limit) dp[pos][cnt] = res;
        return res;
    }

  

猜你喜欢

转载自www.cnblogs.com/hyserendipity/p/12690375.html
今日推荐