打印从1到最大的n位数
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
示例 1:
输入: n = 1 输出: [1,2,3,4,5,6,7,8,9]
说明:
用返回一个整数列表来代替打印 n 为正整数
方法一:字符串 -->数字
public class MAain {
StringBuilder res;
int n;
char[] num, loop = {'0', '1', '2', '3', '4', '5', '6', '7','8','9'};
public String printf(int n){
this.n = n;
res = new StringBuilder(); //数字字符串集,res是用来储存最后字符串结果的
num = new char[n]; //长度为n的字符串,num是记录位数的
dfs(0); //递归
res.deleteCharAt(res.length() - 1); //去掉最后的逗号
return res.toString();
}
void dfs(int x){
if(x == n){ //运行到了第n位
//所有数都会运行到这步,例如:0001
res.append(String.valueOf(num) + ","); //拼接num并添加至rea尾部,然后吧每个数用逗号隔开,最结尾多个括号
return;
}
for(char i : loop){ //遍历0-9
num[x] = i; //固定第x位为i 0 - 9
dfs(x + 1); //开始固定第x+1位
//直到把所有数的遍历完
}
}
}
class Solution {
int[] res;
int nine = 0, count = 0, start, n;
char[] num, loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public int[] printNumbers(int n) {
this.n = n;
res = new int[(int)Math.pow(10, n) - 1]; //创建数组
num = new char[n]; //位数
start = n - 1; //n-1
dfs(0); //深度
return res;
}
void dfs(int x) {
if(x == n) { //
String s = String.valueOf(num).substring(start);
if(!s.equals("0")) res[count++] = Integer.parseInt(s);
if(n - start == nine) start--;
return;
}
for(char i : loop) {
if(i == '9') nine++;
num[x] = i;
dfs(x + 1);
}
nine--;
}
}