leecode 解题总结:357. Count Numbers with Unique Digits

#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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])

分析:给定一个非负整数n,输出0到10^n有多少非唯一的数字组成的数的个数,该整数
是n位数。
举例:
n=2,就是11,22,33,44,55,66,77,88,99 是唯一的数字组成,需要排除,10^2 - 9 = 91
n=3,就是,11,22,33,44,55,66,77,88,99,111,222,333,...,999
     不对:112,这种也需要排除
	 等于是{11,22,33,44,55,66,77,88,99} 与 {0,1,2...,9}的组合的也需要排除
	 我们先计算:
	 1】
	 {11,22,33,44,55,66,77,88,99} 与 {1,2...,9}重复的个数
	 以1为例1和11本身只计数1个,
	 1和22,由于1可以插入在22中3个位置,形成122,212,221,所有共有3个,
	 共计:1 + 8 * 3 = 25
	 同理其他8个数也是这样,所以{1,2...,9}与{11,22,33,44,55,66,77,88,99} 
	 组成的3位数中计数=9 * 25 = 225
	 2】
	 来看0,以11为例,头部不可以插入,有2个位置101,110,
	 所以共计=2 * 9 = 18
	 所以n=3时,3位数中存在某些位相同的总共是计数=9 * (1 + 8 * 3) + 2 * 9
	 总结规律:n=3,3位数计数=9*(1 + 8 * n) + (n-1) * 9
	           n=2,2位数计数=9
			   n=4,4位数计数=9*(1 + 8 * n) + (n-1) * 9。
			   不对存在: 1213什么的也是重复,可以在
			   121中插入{1,9}
所以当n=2时,总的计数=9
当n > 2时,计数1= 累加和(  9*(1 + 8 * i) + (i-1) * 9 ),i属于3到n
           总的计数=9 + 计数1
最后再拿10^n - 总的计数即可

参考leecode提示:
This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics.
Let f(k) = count of numbers with unique digits with length equals k.
f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
直接统计存在相同位的数字太麻烦,因此直接统计不同的数字。
根据排列问题,设f(i)表示长度为i的所有数字中各个位都不同的数字个数
那么作为每个数的最高位:可以从{1,2,..,9}中任意选择一个,记为i,有9种,
次最高位可以从{0,1,2...,9}中选择除了i之外剩余9个【易错】,
则f(1)=10,f(2)=9*9
总结
f(1)=10;
k >= 2时,
f(k)=9 * 9 * 8* ..*(9-k+2),k最多为10,如果k为11,11位数必定有位数重复
k >= 11,f(k)=0
然后把f(1)+f(2)+...+f(k)累加起来

输入:
0
1
2
3
输出:
10
91
739


关键:
1
直接统计存在相同位的数字太麻烦,因此直接统计不同的数字。
设f(i)表示长度为i的所有数字中各个位都不同的数字个数
那么作为每个数的最高位:可以从{1,2,..,9}中任意选择一个,记为i,有9种,
次最高位可以从{0,1,2...,9}中选择除了i之外剩余9个【易错】,
则f(1)=10,f(2)=9*9
总结
f(1)=10;
k >= 2时,
f(k)=9 * 9 * 8* ..*(9-k+2),k最多为10,如果k为11,11位数必定有位数重复
k >= 11,f(k)=0
然后把f(1)+f(2)+...+f(k)累加起来
2 易错,统计0~10^n,若为0,1必定是
*/

class Solution {
public:
    int countNumbersWithUniqueDigits(int n) {
		if(n < 0)
		{
			return 0;
		}
		//易错,统计0~10^n,若为0,1必定是
		if(0 == n)
		{
			return 1;
		}
        vector<int> dp(n + 1 , 0);
		dp.at(1) = 10;
		int temp = 1;
		int result = dp.at(1);
		for(int i = 2 ; i <= n ; i++)
		{
			if(9 - i + 2 >= 1)
			{
				temp *= (9 - i + 2);
				dp.at(i) = 9 * temp;
				result += dp.at(i);
			}
			else
			{
				break;
			}
		}
		return result;
		
    }
};


void process()
{
	 int num;
	 Solution solution;
	 int result;
	 while(cin >> num )
	 {
		 result = solution.countNumbersWithUniqueDigits(num);
		 cout << result << endl;
	 }
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}



版权声明:本文为qingyuanluofeng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。