您的位置:首页 > 产品设计 > UI/UE

LeetCode No.357 Count Numbers with Unique Digits

2016-10-28 21:33 417 查看
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]
)

====================================================================================

原题地址:https://leetcode.com/problems/count-numbers-with-unique-digits/

题目大意是:给定一个非负整数n,求出在 0 ≤ x < 10n 中满足x每位数字都不相同的个数。

这道题目很显然是一道动态规划(DP)题目,构建一个长度为n+1的数组dp[n+1],其中dp[i]表示i位数中满足条件的x的个数。

根据数学中的排列组合公式,我们可以得到一个递推式:



最后将dp[0]到dp
之间的值加起来就行了,其中需要注意的是,因为没有11位的满足条件的x,当n>10的时候,其实结果也是等于dp[10]的。

附上代码:

class Solution {
public:
int countNumbersWithUniqueDigits(int n) {
vector <int> dp ( 11 , 0 ) ;
dp[0] = 1 ;
dp[1] = 9 ;
for ( int i = 2 ; i <= 10 ; i ++ )
{
dp[i] = dp[i-1] * ( 11 - i ) ;
}
int ans = 0 , maxer = n > 10 ? 10 : n ;
for ( int i = 0 ; i <= maxer ; i ++ )
ans += dp[i] ;
return ans ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: