357. Count Numbers with Unique Digits

来源:互联网 发布:网络系统安全课程 编辑:程序博客网 时间:2024/05/01 03:37
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])


这题比较简单,与其说是一道动规题,不如当成一道数学问题,一位的时候能有十个数,多位的时候第一位只能选择除了零以外的数,而其它位只能选择前面没有出现过的数,所以第二位只有9种选法,第三位只有八种选法...一直以此类推,最后到超过十位的话就不存在合法的数,于是就可以得到相应的解决方法。


实现代码如下:

class Solution {public:    int countNumbersWithUniqueDigits(int n) {        int anw[11];        anw[1]=10;        for(int j=2;j<=10;j++)        {            int temp=9;                for(int i=2;i<=j;i++)            {                temp*=(9-i+2);            }            anw[j]=temp+anw[j-1];        }        if(n==0)        return 1;        if(n>=10)        return anw[10];        return anw[n];    }};


0 0
原创粉丝点击