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

    Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.

    Example:

    Input: 2
    Output: 91 
    Explanation: The answer should be the total numbers in the range of 0 ≤ x < 100, 
                 excluding 11,22,33,44,55,66,77,88,99

    Runtime: 0 ms, faster than 100.00% of C++ online submissions for Count Numbers with Unique Digits.

    额有点蠢。

    f(k) = 9 * 9 * 8 * ... * (9 - i + 2) 第一位是9 因为 0 不能在第一位。

    class Solution {
    public:
        int countNumbersWithUniqueDigits(int n) {
          if(n == 1) return 10;
          vector<int> dp(n+1, 0);
          dp[1] = 9;
          for(int i=2; i<n+1; i++){
            dp[i] = dp[i-1] * (9-i+2);
          }
          int ret = 0;
          for(int i=1; i<n+1; i++) ret += dp[i];
          ret += 1;
          return ret;
        }
      
    };

    DFS

    Runtime: 116 ms, faster than 2.80% of C++ online submissions for Count Numbers with Unique Digits.

    class Solution {
    public:
        int countNumbersWithUniqueDigits(int n) {
          int maxval = pow(10,n), ret = 1, used = 0;
          for(int i=1; i<10; i++){
            used |= (1<<i);
            search(i, maxval, ret, used);
            used &= ~(1<<i);
          }
          return ret;
        }
          void search(int prev, int maxval, int& ret, int& used){
            if(prev < maxval) ret++;
            else return ;
            for(int i=0; i<10; i++){
              if(!(used & (1 << i))){
                used |= (1<<i);
                search(10*prev+i, maxval, ret, used);
                used &= ~(1<<i);
              }
            }
          }
    };
  • 相关阅读:
    信息检索重点句子分析部分
    信息检索重点关键字
    信息检索问答部分
    信息检索重点句子分析部分
    信息检索重点句子分析部分
    信息检索重点句子分析部分
    信息检索问答部分
    信息检索问答部分
    信息检索问答部分
    2007年中国羽毛球大师赛直播时间表
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10196875.html
Copyright © 2011-2022 走看看