- LeetCode #357: Count Numbers wit
- [LeetCode 357] Count Numbers wit
- [LeetCode]357. Count Numbers wit
- Leetcode 357. Count Numbers with
- [leetcode] 357. Count Numbers wi
- LeetCode笔记:357. Count Numbers wi
- Leetcode 357.Count Number With U
- Leetcode解题报告——357. Count Numbers
- 357. Count Numbers with Unique D
- 【LEETCODE】模拟面试-357- Count Number
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Input: 2
Output: 91
Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,
excluding 11,22,33,44,55,66,77,88,99
Solution
一个排列组合的题目,求没有重复数字的数的个数
- 当
n=1
时, 只有一个数字,0-9都是答案. - 当
n>=2
时,最高位可以为1-9任意一个数字,之后各位可以选择的数字个数依次为9, 8, 7, 6...,上一位选一个下一位就少了一种选择.所以,n = 2
时,其组合方式一共有10 + 9 * (10 - 2 + 1)
种 - 以此类推
class Solution {
public int countNumbersWithUniqueDigits(int n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return 10;
}
int productValue = 9;
int result = 10;
for (int i = 2; i <= n; i++) {
productValue = productValue * (10 - i + 1);
result += productValue;
}
return result;
}
}
网友评论