leetcode [357]Count Numbers with Unique Digits

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

Example:

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

题目大意:

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

解法:

  我采用递归的解法求解由不同数字组成的数字个数,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;
    }
}

  其实这道题目可以将问题简化一些。

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

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

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

java:

扫描二维码关注公众号,回复: 6757407 查看本文章
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;
    }
}

猜你喜欢

转载自www.cnblogs.com/xiaobaituyun/p/11139990.html