注意!需考虑大数数组
字符数组转换为int类型:this
字符数组--字符串(String)--int ----s = String.valueOf(num)----Integer.parseInt(s)
用递归表示多层for:具体spa
void def(int n){ if(){ ... return; } for(xxx){ def();在for循环中调用本身 } }
去零。全排列的结果没法避免地会出现[001,002,003...]而不是题目所须要的[1,2,3,...,999]code
输入n | 此时的数 | 此时该数的位数 | subString(start)中的start | 9的个数nine |
---|---|---|---|---|
2 | 09 | 1 | 1 | 1 |
3 | 009 | 1 | 2 | 1 |
3 | 099 | 2 | 1 | 2 |
获得结论:递归
n = start + nine
,所以在知足以上条件时,须要扩大子字符串的范围,即start--。字符串
public class Solution { char[] arr = {'0','1','2','3','4','5','6','7','8','9'}; int n; int[] res; char[] num; int nine,start, k =0; public int[] printNumbers(int n){ this.n = n; res = new int[(int) Math.pow(10,n)-1]; num = new char[n]; start = n-1; def(0); return res; } public void def(int x){ if (x == n){ String s = String.valueOf(num).substring(start); if(s.equals("0")) return; res[k] = Integer.parseInt(s); k++; if (n-start == nine) start--; return; } for (char a : arr) { if (a=='9') nine++; num[x] = a; def(x+1); } nine--; } }
d25string