LeetCode學習篇十二——Count Numbers with Unique Digits

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

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])
難度:medium 通過率:44.4%

一開始看到題目給的例子,除去了11、22、……99,所以一開始想用排除法做,求出有重複數字的數的數目,再用總數目去減,想找出一個規律來,但算着算着發現要考慮很多情況,所以想着直接計算,於是直接用排列組合思想計算即可。用數組count存儲當數字爲i位時不重複數字的個數,然後再直接加起來即可。

class Solution {
public:
    int countNumbersWithUniqueDigits(int n) {
        int sum = 1;
        for(int i = 0; i < n; i++) {
            int temp = 9;   
            for(int j = 9; j >= 10-i; j--) {
                temp *= j;
            }
            sum+=temp;
        }
        return sum;
    }
};
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章