【Jianzhi 17】Print from 1 to the largest n digits

Method 1: Do not consider the overflow of large numbers: time O( 1 0 n 10^n10n ), space O(1)

Solution: Do not consider the case of large numbers overflowing int

class Solution {
    
    
public:
    vector<int> printNumbers(int n) 
    {
    
    
        int count = pow(10, n);
        vector<int> res(count - 1);
        for (int i = 1; i < count; i++)
        {
    
    
            res[i - 1] = i;
        }
        return res;
    }
};

Method 2: Large number printing: time O( 1 0 n 10^n10n ), space O(1 0 n 10^n10n)

answer:

  1. Considering the overflow of large numbers, you need to use strings to count each number
  2. Each number is actually a permutation and combination of 0-9, so the combination of each bit is recursive, and the array is inserted when the combination condition is met
  3. In order to pass the test of the question, use stoi to convert the number to an integer before inserting
class Solution {
    
    
public:
   vector<int> res;
vector<char> board = {
    
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
void dfs(int index, int n, string& str)
{
    
    
    if (index == n)
    {
    
    
        int tmp = stoi(str);
        if (tmp != 0)
            res.push_back(tmp);
        return;
    }
    for (int i = 0; i < board.size(); i++)
    {
    
    
        str.push_back(board[i]);
        dfs(index + 1, n, str);
        str.pop_back();
    }
}
vector<int> printNumbers(int n)
{
    
    
    string str;
    dfs(0, n, str);
    return res;
}
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/112713740