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:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])

題目的意思就是每一位上的數字都不能重複!!!動態規劃思想:

class Solution {
public:
	int countNumbersWithUniqueDigits(int n) {
		if (n == 0)return 1;
		vector<int>re(n + 1, 0);
		re[1] = 10;
		for (int i = 2; i <= n; i++){
			int start = 9;
			int bit = i - 1;
			int sum = 0;
			int pro = 9;
			while (bit){
				pro = pro*start;
				start--;
				if(n>1)sum = sum + re[bit]-re[bit-1];
				else sum = sum + re[1];
				bit--;
			}
			re[i] = pro + sum;
		}
		return re[n];
	}
};

Submission Result: Accepted  More Details 

Share your acceptance!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章