LeetCode学习篇十二——Count Numbers with Unique Digits

来源:互联网 发布:图片文字隐藏算法 编辑:程序博客网 时间:2024/06/06 12:52

题目:Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.

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])
难度:medium 通过率:44.4%

一开始看到题目给的例子,除去了11、22、……99,所以一开始想用排除法做,求出有重复数字的数的数目,再用总数目去减,想找出一个规律来,但算着算着发现要考虑很多情况,所以想着直接计算,于是直接用排列组合思想计算即可。用数组count存储当数字为i位时不重复数字的个数,然后再直接加起来即可。

class Solution {public:    int countNumbersWithUniqueDigits(int n) {        int sum = 1;        for(int i = 0; i < n; i++) {            int temp = 9;               for(int j = 9; j >= 10-i; j--) {                temp *= j;            }            sum+=temp;        }        return sum;    }};
0 0
原创粉丝点击