一、题目描述
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
示例 1:
输入: n = 1
输出: [1,2,3,4,5,6,7,8,9]
说明:
用返回一个整数列表来代替打印
n 为正整数
二、题解
全排列
class Solution {
private int[] res;
private char[] loop = {
'0','1','2','3','4','5','6','7','8','9'};
private char[] num;
private int n;
private int count = 0;
public int[] printNumbers(int n) {
this.n = n;
this.num = new char[n];
this.res = new int[(int)Math.pow(10,n)-1];
dfs(0);
return res;
}
public void dfs(int x){
if(x == n){
if(Integer.parseInt(String.valueOf(num))!=0)
res[count++] = Integer.parseInt(String.valueOf(num));
return ;
}
for(char ch:loop){
num[x] = ch;
dfs(x + 1);
}
}
}
删除高位多余的 00,(由于上题是转化为了整数,如果是字符串的话,会出现001这样的情况,因此需要解决)
class Solution {
private int[] res;
private char[] loop = {
'0','1','2','3','4','5','6','7','8','9'};
private char[] num;
private int n;
private int count = 0;
private int nine = 0;
private int start = 0;
public int[] printNumbers(int n) {
this.n = n;
this.num = new char[n];
this.res = new int[(int)Math.pow(10,n)-1];
this.start = n - 1;
dfs(0);
return res;
}
public void dfs(int x){
if(x == n){
int temp = Integer.parseInt(String.valueOf(num).substring(start));
if(temp!=0)
res[count++] = temp;
if(n-start == nine) start--;
return ;
}
for(char ch:loop){
if(ch == '9') nine++;
num[x] = ch;
dfs(x + 1);
}
nine--;
}
}