LeetCode Count Numbers with Unique Digits
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Count Numbers with Unique Digits相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/count-numbers-with-unique-digits/description/
题目:
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]
)
题解:
f(n)代表n位时有多少number是全用的unique digit的.
f(1) = 10. (0,1,2,3,4,5,6,7,8,9)
f(2) = 9*9. 首位有1到9可选, 二位有0到9除了一位已选的数字可选.
f(3) = f(2)*8. 三位有0到9除了一位二位已选的数字可选.
...
f(10) = f(9)*1.
f(11) = 0 = f(12) = f(13).
最后res是f(1) + f(2) + f(3) + ... + f(n).
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public int countNumbersWithUniqueDigits(int n) { 3 if(n == 0){ 4 return 1; 5 } 6 7 int res = 10; 8 int uniqueCount = 9; 9 int availableNum = 9; 10 while(n>1 && availableNum>0){ 11 uniqueCount *= availableNum; 12 res += uniqueCount; 13 availableNum--; 14 n--; 15 } 16 return res; 17 } 18 }
以上是关于LeetCode Count Numbers with Unique Digits的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 315. Count of Smaller Numbers After Self (逆序数对)
Leetcode: Count Numbers with Unique Digits
[LeetCode] Count Numbers with Unique Digits
Leetcode 315. Count of Smaller Numbers After Self