very intuitive method


  • 0
    N
    public class Solution {
        int n;
        public int countNumbersWithUniqueDigits(int n) {
            this.n = n;
            return dfs(new boolean[10],0) + 1;
        }
        //# of distinct numbers from depth 0 to depth
        int dfs(boolean[] used, int depth) {
            if(depth >= n) {
                return 0;
            }
            int count = 0;
            for (int i = 0; i < 10; i++) {
                if(i == 0 && depth == 0) {
                    continue;
                } 
                if(!used[i]) {
                    used[i] = true;
                    count += 1 + dfs(used,depth + 1);
                    used[i] = false;
                }
            }
            return count;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.