题目:
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
示例 1:
输入: n = 1 输出: [1,2,3,4,5,6,7,8,9]
以下分别展示两种解决,都采用的是递归的解决方法,递归的终止条件都是不谋而合
@RunWith(SpringRunner.class)
public class TestClass {
int[] res;
int nine = 0, count = 0, start, n;
//num表示位数,n==3表示百 十 个
char[] num;
char[] loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
@Test
public void test() {
int[] ans = printNumbers(2);
}
public int[] printNumbers(int n) {
this.n = n;
res = new int[(int) (Math.pow(10, n) - 1)];
num = new char[n];
start = n - 1;
dfs(0);
return res;
}
void dfs(int x) {
if (x == n) {
String s = String.valueOf(num).substring(start);
System.out.println("start = " + start);
System.out.println("num = " + new String(num));
if (!s.equals("0")) {
res[count++] = Integer.parseInt(s);
System.out.println("res [] " + s);
}
if (n - start == nine) {
start--;
System.out.println("start = " + start);
}
return;
}
for (char i : loop) {
System.out.println("char i = " + i);
if (i == '9') nine++;
num[x] = i;
System.out.println("dfs (" + (x + 1) + ")");
dfs(x + 1);
}
System.out.println("loop -> nine = " + nine);
nine--;
}
}
方法二较方法一略微好懂一些。
@RunWith(SpringRunner.class)
public class TestClass {
//num表示位数,n==3表示百 十 个
char[] num;
char[] loop = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
StringBuilder sb = new StringBuilder();
public String printNumber2(int len){
num = new char[len];
for(int i = 1;i<=len;i++){
dfs(0,i);
}
return sb.deleteCharAt(sb.length()-1).toString();
}
public void dfs(int index,int len){
if(index == len){
sb.append(new String(num).trim()+",");
return;
}
int start = 0;
//若从0作为起点:if(index == 0 && len>1)
//若从1作为起点
if(index == 0){
start = 1;
}else{
start = 0;
}
for(int i=start;i<10;i++){
num[index] = loop[i];
System.out.println("start = " + start);
System.out.println("num" + new String(num));
dfs(index+1,len);
}
}
@Test
public void test2() {
System.out.println(printNumber2(3));
}
}