leetcode [357]Count Numbers with Unique Digits

Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.java

Example:git

Input: 2
Output: 91 Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100,   excluding  11,22,33,44,55,66,77,88,99

题目大意:spa

  给一个数字n,找出[0,10^n)这个区间内,由不一样数字组成的数字个数。code

解法:blog

  我采用递归的解法求解由不一样数字组成的数字个数,flag这个整数的第0到9位记录该数字是否被使用过,而tmp则是当前的数字,可是这种解法的效率极低。递归

class Solution {
    int count=1;
    void dfs(int n,int tmp,int flag){
        if (tmp>=Math.pow(10,n)){
            return;
        }
        for (int i=0;i<10;i++){
            if (tmp==0 && i==0) continue;
            if ((flag&(1<<i))==0 && tmp*10+i<Math.pow(10,n)){
                count++;
                dfs(n,tmp*10+i,flag|(1<<i));
            }
        }
    }

    public int countNumbersWithUniqueDigits(int n) {
        int tmp=0,flag=0;
        dfs(n,tmp,flag);

        return count;
    }
}

  其实这道题目能够将问题简化一些。input

  当只有一位数字的时候,有10种结果,f(1)=10。it

  当有两位数字的时候,有9*9种结果,f(2)=9*9。io

  当有三位数字的时候,有9*9*8种结果,f(3)=9*9*8。class

java:

class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if (n==0) return 1;
        int res=10;
        int a=9,b=9;
        n--;
        while (n-->0 && b>0){
            a=a*b;
            res+=a;
            b--;
        }

        return res;
    }
}
相关文章
相关标签/搜索