357. Count Numbers with Unique Digits解题报告

来源:互联网 发布:80年代香港女星 知乎 编辑:程序博客网 时间:2024/05/21 10:34

题目

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

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])

题意解析

题目意思是说,给定一个非负整数n,计算各位数都不一样的个数,数的范围是0到10^n

举个例子,当n=2时,各位数一样的数字是11,22,33,44,55,66,77,88,99,所以各位数不一样的个数是100-9=91个

思路分析

对于n=1,则为10个(0-9)
对于n=2,在最高位有1-9可以选择,总共有9种选择,在次高位有(10-1)种选择
对于n=3,在最高位有1-9可以选择,在次高位有9种可以选择,在最低位有9-1=8种可以选择
则可以得到递推公式:f(n) = 9 * 9 * 8 * (9 - n + 2)
然后把递推公式相加,则得到结果

AC代码

class Solution {public:    int perstep(int k) {        if (k >= 2) {            int res = 1;            for (int i = 9; i >= 11 - k; --i) {                res *= i;            }            return res * 9;        } else if (k == 1) {            return 10;        } else {            return 0;        }    }    int countNumbersWithUniqueDigits(int n) {        if (n == 0) return 1;        int result = 0;        for (int i = 1; i <= n; ++i) {            result += perstep(i);        }        return result;    }};
阅读全文
0 0
原创粉丝点击