zoukankan      html  css  js  c++  java
  • 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

    Approach #1: Math. [C++]

    class Solution {
    public:
        int countNumbersWithUniqueDigits(int n) {
            if (n == 0) return 1;
            if (n == 1) return 10;
            
            int ans = 10;
            int count = 9;
            int temp = 9;
            while (n > 1 && count > 0) {
                temp = temp * count;
                ans += temp;
                count--;
                n--;
            }
            
            return ans;
        }
    };
    

      

    Analysis:

    f(1) = 10;

    f(2) = f(1) + 9 * 9;  xy: x: can be 1, 2.....8, 9.  y: can't be the same as with x but it can be 0, so there are 9 difference kinds choise.

    f(2) = f(2) + 9 * 9 * 8;

    Approach #2: backtracking. [C++]

    public class Solution {
    	public static int countNumbersWithUniqueDigits(int n) {
    		if (n > 10) {
    			return countNumbersWithUniqueDigits(10);
    		}
    		int count = 1; // x == 0
    		long max = (long) Math.pow(10, n);
    
    		boolean[] used = new boolean[10];
    
    		for (int i = 1; i < 10; i++) {
    			used[i] = true;
    			count += search(i, max, used);
    			used[i] = false;
    		}
    
    		return count;
    	}
    
    	private static int search(long prev, long max, boolean[] used) {
    		int count = 0;
    		if (prev < max) {
    			count += 1;
    		} else {
    			return count;
    		}
    
    		for (int i = 0; i < 10; i++) {
    			if (!used[i]) {
    				used[i] = true;
    				long cur = 10 * prev + i;
    				count += search(cur, max, used);
    				used[i] = false;
    			}
    		}
    
    		return count;
    	}
    }
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    列表的排序和统计。
    pyoo6 列表 004
    py005 列表 03
    py004列表02
    py 003 列表01
    py。002 字符串(str)
    py_001 运算符
    【python--字典】 字典的嵌套
    【python--字典】 字典的增删改查
    【python--字典】 字典的有效性
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10353330.html
Copyright © 2011-2022 走看看