文章目录
1. 题目
2. 思路
(1) DFS
- 关键是利用深度优先搜索对每一个长度的数字进行全排列,如一位数字的全排列是1、2、……、9,两位数字的全排列是10、11、……、99,每一个长度的数字其全排列结果的第一位上的数字是1-9,其他位上的数字是0-9。
- 首先单独对第一位赋值,然后递归对其他位赋值,每当对所有位赋完值后,将其加入结果集即可。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
private int[] res;
private int count;
public int[] printNumbers(int n) {
res = new int[(int) Math.pow(10, n) - 1];
count = 0;
char[] num;
for (int digit = 1; digit <= n; digit++) {
for (char first = '1'; first <= '9'; first++) {
num = new char[digit];
num[0] = first;
fullPermutation(num, 1, digit);
}
}
return res;
}
private void fullPermutation(char[] num, int index, int digit) {
if (index == digit) {
res[count++] = Integer.parseInt(String.valueOf(num));
return;
}
for (char i = '0'; i <= '9'; i++) {
num[index] = i;
fullPermutation(num, index + 1, digit);
}
}
}