【357】Count Numbers with Unique Digits
来源:互联网 发布:2013旧版qq软件 编辑:程序博客网 时间:2024/06/05 04:15
题目:
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为i时,输出结果为res[ i ];
当 n = 0 时,res[ 0 ]=1;
当 n = 1 时,res[ 1 ] = 9 + res[ 0 ];
当 n = 2 时,若该数字为两位数,那么0在个位时有9种情况,没有0时有9*8种情况;再加上该数字为一位数时的情况,即n=1时的情况。
res[ 2 ]= 9 + 9 * 8 + res[ 1 ] = 9 * ( 1 + 8 ) + res[ 1 ];
当 n = 3 时,若该数字为三位数,0在个位时有9*8种情况,0在十位时有9*8种情况,没有0时有9*8*7种情况;再加上n=2时的情况,即为最终结果。
res[ 3 ] = 9 * 8 + 9 * 8 + 9 * 8 * 7 + res[ 2 ] = 9 * 8 * (7+1+1) + res[ 2 ];
可以推出:
当n = 0 时,res[ 0 ]=1;
当n = 1 时,res[ 1 ] = 9 + res[ 0 ];
当n = i ( 1< i <= 10) 时,res[ i ] = 9 * 8 *...* (10 - i + 1 ) * 9 + res[ i - 1 ];
当n > 10 时, res[ n ] = 0;
代码:
class Solution {public: int countNumbersWithUniqueDigits(int n) { int c=9; int res; if(n==0) return 1; if(n==1) return 10; if(n>10) return 0; else { for (int i=9;i>10-n;i--) { c *= i; } res = c + countNumbersWithUniqueDigits(n-1); return res; } }};
- LeetCode 357 Count Numbers with Unique Digits
- LeetCode[357] Count Numbers with Unique Digits
- LeetCode 357 Count Numbers with Unique Digits
- [357]Count Numbers with Unique Digits
- leetcode 357 Count Numbers with Unique Digits
- Leetcode #357 Count Numbers with Unique Digits
- LeetCode 357: Count Numbers with Unique Digits
- 【357】Count Numbers with Unique Digits
- Leetcode 357 Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- Count Numbers with Unique Digits
- 在园区网中实施VLAN
- L1-034. 点赞
- Item37 Make std::threads unjoinable on all paths
- fl2440 linux内核移植usb驱动
- Git版本管理工具的学习
- 【357】Count Numbers with Unique Digits
- NYOJ 小珂的烦恼
- 日常收集有用的网址:
- spring整合struts2和hibernate在删除关联数据的时候特别注意
- 【剑指offer之反转链表】九度OJ-1518-反转链表
- JAVA基本类型与包装类
- 【C++学习笔记】递增/递减运算符和指针
- 继承中的public,protected,private
- windows系统与虚拟机下的linux系统相互传输文件