357. Count Numbers with Unique Digits

题目链接:https://leetcode.com/problems...

和安卓解锁那道题很想,那道题步数是m到n,
https://segmentfault.com/a/11...
这道题是1到n,表示数字的位数。backtracking,每次要记录走到的位数作为depth,从msb开始。dp[i]: # of numbers with (i+1) unique digits, dp[0] = 9, dp[i] = (n - i) * dp[i-1],最后结果是sum(dp[i]),i = [0, n-1], 也可以dfs来做, bottom up。注意最后0的情况,只有一位的时候算上0,一位以上,首位都不可以是0。

public class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if(n == 0)  return 1;
        
        int[] dp = new int[Math.min(n, 10)];
        dp[0] = 9;
        // count 0
        int result = 1 + dp[0];
        for(int i = 1; i < Math.min(n, 10); i++) {
            dp[i] = (10 - i) * dp[i-1];
            result += dp[i];
        }
        
        return result;
    }
}

滚动数组优化空间到O(1)

public class Solution {
    public int countNumbersWithUniqueDigits(int n) {
        if(n == 0)  return 1;
        
        int dp = 9;
        // count 0
        int result = 1 + dp;
        for(int i = 1; i < Math.min(n, 10); i++) {
            dp = (10 - i) * dp;
            result += dp;
        }
        
        return result;
    }
}

lulouch13
13 声望6 粉丝