Google面试题 | 数字计数

Description

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding[11,22,33,44,55,66,77,88,99])

Solution

题目给了两种解法:回溯搜索和DP,这里用DP方程解决:
f(k) 为k个不等数字组成的数的个数,则有
f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (11 - k) [第一个因子为0是因为非0数不能以0开头]
利用上面的递推式,提前计算好答案存在数组中直接返回,需要注意对n大于10的处理

Code

class Solution {
private:
    int f[11];
public:
    Solution() {
        f[0] = 1; f[1] = 10;
        int t = 9, cnt = 9;
        for (int i=2; i<=10; i++) {
            cnt *= t--;
            f[i] = f[i-1] + cnt;
        }
    }

    int countNumbersWithUniqueDigits(int n) {
        if (n > 10) n = 10;
        return f[n];
    }
};

LeetCode: 357. Count Numbers with Unique Digits

点赞