• leetcode 之 Count Numbers with Unique Digits


    题目描述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]) 
    
    Hint:
    1.A direct way is to use the backtracking approach.
    2.Backtracking should contains three states which are (the current number, 
    number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number).
    Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. 3.This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. 4.Let f(k) = count of numbers with unique digits with length equals k. 5.f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
    即给定一个整数n, 计算从[0, 10^n)中,所有不含重复数字的数的个数

    1. 回溯:

    输入n的话, 不考虑10^n, 则总共有n位数. 使用 cur[n] 代表当前的数字. 使用一个flag[10] 代表0~9位数字,  每次放入一个数字,则flag对应的数字置为1,

    代码如下:

    class Solution(object):
        def countNumbersWithUniqueDigits(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n == 0:
                return 1
            flag = [0]*10
            cur = [0]*n
            step = 0;
            count = [0];
            self.helper(0, flag, cur, count, n)
            return count[0] 
        def helper(self, step, flag, cur, count, n):
            if step >= n:
                count[0] += 1
                return
            for i in range(0, 10):
                if flag[i] != 1 or (i==0 and step !=n and sum(cur[step:])==0):  #解决诸如[0,0,0], [0, 1,0]这类数字不能统计的问题
                    cur[step] = i
                    flag[i] = 1
                    self.helper(step+1, flag, cur, count, n)
                    flag[i] = 0
                else:
                    continue

    上述回溯法,在时间上超时了T_T

    2.动态规划:

    根据提示4,  f(k) = 9 * 9 *...(9-k+2)

    class Solution(object):
        def countNumbersWithUniqueDigits(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n == 0:
                return 1
            if n == 1:
                return 10
            res = 0
            for i in range (1, n+1):
                res += self.count(i)
            return res
        def count(self, num):
            if num == 0 : return 1
            if num == 1: return 10
            res = 1
            for i in range(9, 11-num-1, -1):
                res *= i
            return res*9
    ~~~~~
  • 相关阅读:
    访友
    幼儿园分班
    求一个数的平方根
    计数器
    连续数组的最大和
    给定一个权重数组,实现一个带权重的路由策略
    两个超长字符串相加
    参数解析(得到输入参数)
    对字符串中的所有单词进行倒排。
    推荐PHP程序员进阶的好书
  • 原文地址:https://www.cnblogs.com/missmzt/p/5714948.html
Copyright © 2020-2023  润新知