zoukankan      html  css  js  c++  java
  • [leetcode-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])

    思路:

    思路:

    排列组合题。

    设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;
         }
  • 相关阅读:
    vertical-align
    剑指offer刷题
    ES6 promise
    wangyi准备
    spring定时器
    xshell下linux常用操作
    HSSFWorkbook生成excel文件
    梳理并分解继承体系
    JSON格式数据转换
    部署项目
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/7069573.html
Copyright © 2011-2022 走看看