【Leetcode】357. Count Numbers with Unique Digits
2016-06-13 20:20
411 查看
题目描述:
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
解题分析:
题目要就就是找出 0≤ x < 10n中各位数字都不相同的数的个数。要接触这道题只需要理解:
1.设f(n)表示n为数字中各位都不相同的个数,则有countNumbersWithUniqueDigits(n)=f(1)+f(2)+……+f(n)=f(n)+countNumbersWithUniqueDigits(n-1);
2.对于f(n),由于首位不能为0,之后n--1位可以选不重复的任意数字,所以这是一个高中常见的概率题,可能性为9*9*8*……(所以可能出现的不可能超过10位);
理解了以上两点,这道题就很好得出。
具体代码:
public class Solution { public static int countNumbersWithUniqueDigits(int n) { if(n<0) return 0; if(n==0){ return 1; } if(n==1) return 10; if(n==2) return 91; int sum=9; int index=0; while(index<n-1){ int m=9-index; if(m<=0) break; sum=sum*m; index++; } int result = sum+countNumbersWithUniqueDigits(n-1); return result; } }
相关文章推荐
- [LeetCode] Minimum Path Sum
- leetcode - Search a 2D Matrix
- Leetcode_populating-next-right-pointers-in-each-node(updated c++ and python version)
- leetcode: Text Justification
- 【LeetCode】Algorithms 题集(三)
- LeetCode:Sum Root to Leaf Numbers
- 《leetCode》:Merge Two Sorted Lists
- leetcode -- Range Sum Query 2D - Immutable -- 简单DP题目
- leetcode 279. Perfect Squares
- leetcode: Substring with Concatenation of All Words
- Leetcode 317. Shortest Distance from All Buildings
- leetcode 231
- [LeetCode]Buy and Sell Stocks 买卖股票问题
- LeetCode 347 Top K Frequent Elements (HashMap && TreeMap 或 PriorityQueue 推荐)
- LeetCode Text Justification
- 和大神们学习每天一题(leetcode)-Path Sum
- 83. Remove Duplicates from Sorted List Leetcode Python
- 【leetcode】Container With Most Water
- leetcode 日经贴,Cpp code -Minimum Window Substring
- [LeetCode]Longest Substring Without Repeating Characters