超時(shí)了超時(shí)了嫂粟。刽漂。但我覺得是對的
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n < 1:
return 1
if n == 1:
return 10
i = 1
res = 0
while i <= n:
visit = [0 for j in range(10)]
count = [0]
self.backtrack(i, count, [], visit)
res += count[0]
i += 1
return res
def backtrack(self, num, count, temp, visit):
if len(temp) == num:
if temp[0] == 0 and num != 1:
return
else:
count[0] += 1
return
for i in range(10):
if visit[i] == 0:
visit[i] = 1
self.backtrack(num, count, temp+[i], visit)
visit[i] = 0
一種用排列組合公式做的:
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n < 1:
return 1
if n == 1:
return 10
i = n
res = 0
while i > 1:
count = 9
j = 9
for m in range(i-1):
count *= j
j -= 1
res += count
i -= 1
return res + 10
這一題的具體的一個(gè)說明:
This is a digit combination problem. Can be solved in at most 10 loops.
When n == 0, return 1. I got this answer from the test case.
When n == 1, _ can put 10 digit in the only position. [0, ... , 10]. Answer is 10.
When n == 2, _ _ first digit has 9 choices [1, ..., 9], second one has 9 choices excluding the already chosen one. So totally 9 * 9 = 81. answer should be 10 + 81 = 91
When n == 3, _ _ _ total choice is 9 * 9 * 8 = 684. answer is 10 + 81 + 648 = 739
When n == 4, _ _ _ _ total choice is 9 * 9 * 8 * 7.
...
When n == 10, _ _ _ _ _ _ _ _ _ _ total choice is 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
When n == 11, _ _ _ _ _ _ _ _ _ _ _ total choice is 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 0 = 0
按照這種寫法
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 1
ans = 10
base = 9
for i in range(2, min(n+1, 11)):
base = base *(9-i+2)
ans += base
return ans