Print numbers from 1 to the largest number with N digits by recursion.
Notice
It's pretty easy to do recursion like:
recursion(i) {
if i > largest number:
return
results.add(i)
recursion(i + 1)
}
however this cost a lot of recursion memory as the recursion depth maybe very large. Can you do it in another way to recursive with at most N depth?
Example
Given N = 1
, return [1,2,3,4,5,6,7,8,9]
.
Given N = 2
, return[1,2,3,4,5,6,7,8,9,10,11,12,...,99]
.
Runtime: 179ms.
1 class Solution { 2 public: 3 /** 4 * @param n: An integer. 5 * return : An array storing 1 to the largest number with n digits. 6 */ 7 vector<int> numbersByRecursion(int n) { 8 // write your code here 9 vector<int> result; 10 if (n <= 0) return result; 11 12 printNumbers(result, 0, n); 13 return result; 14 } 15 16 private: 17 void printNumbers(vector<int>& result, int depth, int n) { 18 if (depth >= n) return; 19 20 int copyNumber = result.size(); 21 for (int i = 1; i <= 9; i++) { 22 int base = i * pow(10, depth); 23 result.push_back(base); 24 for(int j = 0; j < copyNumber; j++) { 25 result.push_back(base + result[j]); 26 } 27 } 28 printNumbers(result, depth + 1, n); 29 } 30 };