版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjucor/article/details/88616346
Given a positive integer N
, return the number of positive integers less than or equal to N
that have at least 1 repeated digit.
Example 1:
Input: 20
Output: 1
Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.
Example 2:
Input: 100
Output: 10
Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.
Example 3:
Input: 1000
Output: 262
Note:
1 <= N <= 10^9
思路:求出没有重复的总数A,然后N-A就是结果。求A可以用DFS,开一个数组ps表示前面用了什么数字,要注意首位为0的情况(最烦这种题了...)
class Solution(object):
def numDupDigitsAtMostN(self, N):
"""
:type N: int
:rtype: int
"""
def fac(n,cnt):
res=1
for i in range(n,n-cnt,-1): res*=i
return res
def all_diff(n,idx,ps):
if idx==len(str(n)): return 1
res = 0
dig = int(str(n)[idx])
for i in range(dig):
if i in ps: continue
if idx==0 and i==0:
for j in range(i+1,len(str(n))):
res+=9*fac(9,len(str(n))-j-1)
else:
res+=fac(10-len(ps)-1,len(str(n))-idx-1)
if dig not in ps:
ps.append(dig)
res+=all_diff(n,idx+1,ps)
ps.pop()
return res
t = all_diff(N,0,[])
# print(t)
return N-t