码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Count Numbers with Unique Digits

时间:2017-09-26 14:49:16      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:tar   pac   targe   range   turn   ati   uniq   ==   .com   

原题链接在这里:https://leetcode.com/problems/count-numbers-with-unique-digits/description/

题目:

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])

题解:

f(n)代表n位时有多少number是全用的unique digit的.

f(1) = 10. (0,1,2,3,4,5,6,7,8,9)

f(2) = 9*9. 首位有1到9可选, 二位有0到9除了一位已选的数字可选.

f(3) = f(2)*8. 三位有0到9除了一位二位已选的数字可选.

...

f(10) = f(9)*1.

f(11) = 0 = f(12) = f(13).

最后res是f(1) + f(2) + f(3) + ... + f(n).

Time Complexity: O(n). Space: O(1).

AC Java:

 1 class Solution {
 2     public int countNumbersWithUniqueDigits(int n) {
 3         if(n == 0){
 4             return 1;
 5         }
 6         
 7         int res = 10;
 8         int uniqueCount = 9;
 9         int availableNum = 9;
10         while(n>1 && availableNum>0){
11             uniqueCount *= availableNum;
12             res += uniqueCount;
13             availableNum--;
14             n--;
15         }
16         return res;
17     }
18 }

 

LeetCode Count Numbers with Unique Digits

标签:tar   pac   targe   range   turn   ati   uniq   ==   .com   

原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7596497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!