Problem : https://leetcode.com/problems/count-numbers-with-unique-digits/
The input number N means the maximum number of digits we can have for the wanted numbers.
Let F(N) = valid number of unique digits combination for N digits
F(0) = 0. Wanted number = 0. Total number = 1
F(1) = 1. Wanted number = [0 ... 9]. Total number = 10
F(2) = 9 * 9 + F (1) = 91. The first digit has 9 options from 1 to 9. The second digit has 9 options from 0 to 9 ( excluding the digit used by the first digits)
F(3) = 9 * 9 * 8 + F(2) + F(1)
class Solution:
def countNumbersWithUniqueDigits(self, n: int) -> int:
if n == 0:
return 1
if n == 1:
return 10
result = 9
digits = 9
# calculate valid combiations of N digits
for _ in range(1,n):
result *= digits
digits -= 1
return result + self.countNumbersWithUniqueDigits(n-1)
No comments:
Post a Comment