解题报告-1012. Numbers With Repeated Digits

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
class Solution(object):
    def numDupDigitsAtMostN(self, N):
        """
        :type N: int
        :rtype: int
        """
        list_n = map(int, str(N + 1))
        res = 0
        len_n = len(list_n)
        
        def get_cnt(m, n):
            if 0 == n: 
                return 1
            return get_cnt(m, n - 1) * (m - n + 1)
        
        for i in range(1, len_n):
            res += 9 * get_cnt(9, i - 1)
            
        s = set()
        for i, x in enumerate(list_n):
            for y in range(0 if i else 1, x):
                if y in s:
                    continue
                res += get_cnt(9 - i, len_n - i - 1)
            if x in s:
                break;
                
            s.add(x)
        
        return N - res
        # return get_permutation_cnt(3)
        
posted @ 2019-04-11 20:30  JinleiZhang  阅读(319)  评论(0编辑  收藏  举报