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
====================================================================================
原题地址: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 ;
}
};
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 ;
}
};
相关文章推荐
- LeetCode--No.357--Count Numbers with Unique Digits
- [LeetCode] Count Numbers with Unique Digits 计算各位数值不同的数的个数
- leetcode 357 c++. Count Numbers with Unique Digits
- [LeetCode] Count Numbers with Unique Digits
- LeetCode | Count Numbers with Unique Digits
- LeetCode Count Numbers with Unique Digits(计数问题)
- LeetCode 357 Count Numbers with Unique Digits
- Count Numbers with Unique Digits -- LeetCode
- LeetCode 357 Count Numbers with Unique Digits (排列组合)
- [LeetCode]Count Numbers with Unique Digits
- leetcode:数学:Count Numbers with Unique Digits(357)
- Leetcode 357 Count Numbers with Unique Digits
- leetcode:Count Numbers with Unique Digits
- LeetCode: Count Numbers with Unique Digits
- 【LEETCODE】357- Count Numbers with Unique Digits [Python]
- leetcode Count Numbers with Unique Digits
- Leetcode: Count Numbers with Unique Digits
- LeetCode 357: Count Numbers with Unique Digits
- LeetCode: Count Numbers with Unique Digits
- 357.[LeetCode]Count Numbers with Unique Digits