Problem
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]
)
Solution: Math
f(0) = 1 (0)
f(1) = 10 (0 – 9)
f(2) = 9 * 9 (1-9 * (0 ~ 9 exclude the one from first digit))
f(3) = 9 * 9 * 8
f(4) = 9 * 9 * 8 * 7
…
f(x) = 0 if x >= 10
ans = sum(f[1] ~ f[n])
Time complexity: O(1)
Space complexity: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Running time: 0 ms class Solution { public: int countNumbersWithUniqueDigits(int n) { if (n == 0) return 1; vector<int> f(11); f[1] = 10; f[2] = 9 * 9; for (int i = 3; i <= 10; ++i) f[i] = f[i - 1] * (10 - i + 1); int ans = 0; for (int i = 0; i <= min(10, n); ++i) ans += f[i]; return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment