中等 用递归打印数字
24%
通过
用递归的方法找到从1到最大的N位整数。
您在真实的面试中是否遇到过这个题?Yes
样例
给出 N = 1
,
返回[1,2,3,4,5,6,7,8,9]
.
给出 N = 2
,
返回[1,2,3,4,5,6,7,8,9,10,11,...,99]
.
用字符串模拟数字
class Solution {
public:
/**
* @param n: An integer.
* return : An array storing 1 to the largest number with n digits.
*/
vector<int> numbersByRecursion(int n) {
// write your code here
vector<int> res;
if (n ==0) {
return res;
}
char *num = new char[n+1];
num[n] = '\0';
for (int i = 0; i < 10; ++i) {
num[0] = i + '0';
recursion(num,n,0,res);
}
delete [] num;
return res;
}
void recursion(char * num,int length,int index,vector<int>& res) {
if (index == length-1) {
int a = atoi(num);
if(a != 0) {
res.push_back(a);
}
return;
}
for (int i=0; i< 10; i++) {
num[index + 1] = i +'0';
recursion(num,length, index+1 ,res);
}
return;
}
};