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

[leetcode-357-Count Numbers with Unique Digits]

时间:2017-06-23 15:32:04      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:重复   tps   his   target   code   http   pre   nbsp   blank   

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

思路:

思路:

排列组合题。

设i为长度为i的各个位置上数字互不相同的数。

  • i==1 : 1 0(0~9共10个数,均不重复)
  • i==2: 9 * 9 (第一个位置上除0外有9种选择,第2个位置上除第一个已经选择的数,还包括数字0,也有9种选择)
  • i ==3: 9* 9 * 8 (前面两个位置同i==2,第三个位置除前两个位置已经选择的数还有8个数可以用)
  • ……
  • i== n: 9 * 9 * 8 *…… (9-i+2)

需要注意的是,9- i + 2 >0 即 i < 11,也就是i最大为10,正好把每个数都用了一遍。

参考自:https://www.hrwhisper.me/leetcode-count-numbers-unique-digits/

int countNumbersWithUniqueDigits(int n)
     {   
         if (n == 0)return 1;
         if (n == 1)return 10;
         vector<int>dp(n+1,9);
         n = min(n,10);
         int cnt = 10;
         for (int i = 2; i <= n;i++)
         {
             int j = 11 - i;
             dp[i] = dp[i - 1] * j;
             cnt += dp[i];
         }
         return cnt;
     }

 

[leetcode-357-Count Numbers with Unique Digits]

标签:重复   tps   his   target   code   http   pre   nbsp   blank   

原文地址:http://www.cnblogs.com/hellowooorld/p/7069573.html

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