LeetCode 357. Count Numbers with Unique Digits 题解(C++)
2016-10-14 16:12
323 查看
LeetCode 357. Count Numbers with Unique Digits 题解(C++)
题目描述
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10^n.举例
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])思路
用动态规划来完成这道题。f(i)表示位数为i且里面每一位的数字都是唯一的数字个数。比如:f(1)=10;
f(1)=9*9,第一个9是从1~9中选择一个数字(因为0不能当做两位数的第一个数),第二个9是从0~9中选择一个数字(除去第一次已经选择过,这次不能选择的数字),共9种可能;
f(2)=9*9*8,前两个9的意义同上,第三个数8是从除去前两次选择的数字,剩下的8个数字中选择一个;
……
f(10)=9*9*8*7*…*1;
f(11)=f(12)=…=0,因为拥有超过10位数的数字,至少会有其中两个位数的值是一样的;
由上面的分析,若n=0,则结果result为1;
若n=1,则result=f(1)=10;
若n=2,则result=f(1)+f(2)=91;
…….
如此类推,我们需要在代码中创建两个变量,一个保存结果result,每次将当前的结果累加,另一个变量是保存f(i)的值,每次循环进行累乘获取当前的f(i)。
代码
class Solution { public: int countNumbersWithUniqueDigits(int n) { if (n == 0) { return 1; } int result = 10; int uniqueDigits = 9; for (int i = 2; i <= n && i <= 10; ++i) { uniqueDigits *= (9 - i + 2); result += uniqueDigits; } return result; } };
相关文章推荐
- House Robber[leetcode]题解 c++
- LeetCode题解:Range Sum Query - Immutable(C++版本)
- LeetCode 404. Sum of Left Leaves 题解(C++)
- LeetCode 237. Delete Node in a Linked List 题解(C++)
- LeetCode 383. Ransom Note 题解(C++)
- LeetCode题解汇总(C++ Java Python,含题目翻译)
- LeetCode 347. Top K Frequent Elements 题解(C++)
- LeetCode 260. Single Number III 题解(C++)
- LeetCode 167. Two Sum II - Input array is sorted 题解(C++)
- LeetCode 384. Shuffle an Array 题解(C++)
- LeetCode题解:Range Sum Query - Immutable(C++版)
- LeetCode 371. Sum of Two Integers 题解(C++)
- LeetCode 406. Queue Reconstruction by Height 题解(C++)
- LeetCode 283. Move Zeroes 题解(C++)
- LeetCode 409. Longest Palindrome 题解(C++)
- leetcode Minimum Depth of Binary Tree C++题解
- LeetCode 344. Reverse String 题解(C++)
- LeetCode 104. Maximum Depth of Binary Tree 题解(C++)
- LeetCode 382. Linked List Random Node 题解(C++)
- LeetCode 100. Same Tree 题解(C++)