357. Count Numbers with Unique Digits

来源:互联网 发布:股票交易系统测试软件 编辑:程序博客网 时间:2024/05/22 17:34

357. Count Numbers with Unique Digits          

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

         刚学了动态规划,来做几个题。这个题是说给你一个非负数n,求在(0 ≤ x < 10^n)中没有重复数字的x的个数。如n=2时,返回91。

        我列举了0-4的推导:

        n    0       f(0)    1

              1       f(1)    (9+f(0))

              2       f(2)    (9*9+f(2))

              3       f(3)    (9*9*8+f(3))

              4       f(4)    (9*9*8*7+f(4))

        可以看出f(n) = 9*9*8*……*(9-n+2)+f(n-1)

        这样就可以很快做出来了。

class Solution {public:int countNumbersWithUniqueDigits(int n) {if (n == 0) return 1;int j = n - 1;int x = 9;int i = 9;while (j--) {x = x*i;i--;}return x + countNumbersWithUniqueDigits(n - 1);}};


0 0
原创粉丝点击