当前位置:网站首页>17. print from 1 to the maximum n digits

17. print from 1 to the maximum n digits

2022-06-12 05:20:00 Be your goat

The finger of the sword Offer 17. Print from 1 To the biggest n digit

Ideas : Divide and conquer algorithm / Full Permutation

For Large Print , Consider that large numbers are out of bounds . So we need to solve :

  1. Represents the variable type of a large number :string
  2. Generate a string set of numbers :int Carry of type cannot be applied to string type , Consider using n Bit 0-9 The whole arrangement , It can avoid carry operation
  3. Recursively generate a full permutation : Based on the idea of divide and conquer algorithm , Fix the high position first , Recursion to low position , When all bits are fixed , Add string
class Solution {
public:
    vector<int> nums;
    string s;
    vector<int> printNumbers(int n) {
        s.resize(n);
        dfs(n,0);
        return nums;
    }

    void dfs(int end,int index){
        if(end==index){
            int i=0;
            while(i<s.size()&&s[i]=='0')++i;
            if(i!=s.size())
                nums.push_back(stoi(s.substr(i)));
            return;
        }

        for(int i=0;i<=9;++i){
            s[index]='0'+i;
            dfs(end,index+1);
        }
    }
};

Time complexity O( 1 0 n 10^n 10n)

Spatial complexity O(n)

原网站

版权声明
本文为[Be your goat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010618458770.html