zoukankan      html  css  js  c++  java
  • 357. Count Numbers with Unique Digits

    题目:

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

    思路:

      这道题要求0 ≤ x < 10n中,每一位都不相同的数的总数。本质上,这是一道概率题。

      当n=0时,个数为1;

      当n=1时,个数为10;

      当n=2时,若十位为1,个位可选择的数为[0,2,3,4,5,6,7,8,9],共9个数;若十位为2,个位可选择的数为[0,1,3,4,5,6,7,8,9],共9个数……因此当 0 ≤ x < 100时,十位可选择的数为9个,对应个位可选择的数为9个,故在两位数中,不相同的数共有9*9=81个,再加上一位数中不相同的10个数,共有81+10=91个。

      当n=3时,百位可选择的数为9个,十位可选择的数为9个,个位可选择的数为8个,故在三位数中,不相同的数共有9*9*8=648个,再加上两位数和一位数中不同的数,共有648+91=739个。

    代码:

     1 class Solution {
     2 public:
     3     int countNumbersWithUniqueDigits(int n) {
     4         if(n == 0){
     5             return 1;
     6         }
     7         int res = 10;
     8         int sum = 9;
     9         for(int i = 2;i <= n;i++){
    10             sum *= (11-i);
    11             res += sum;
    12         }
    13         return res;
    14     }
    15 };
  • 相关阅读:
    HDU1251统计难题map+输入
    HDU1863畅通工程
    POJ2253 Frogger
    HDU 4725 (The Shortest Path in Nya Graph)层次网络
    hdu5521(Meeting)spfa 层次网络最短路
    Fire Net ZOJ 1002
    POJ3259(Wormholes) 判断负环
    POJ3268(Silver Cow Party)
    棋盘问题 POJ 1321
    POJ 1661 (Help Jimmy )
  • 原文地址:https://www.cnblogs.com/sindy/p/6984578.html
Copyright © 2011-2022 走看看