题目传输地址: ​​https://leetcode.cn/problems/permutations/submissions/​

Leetcode46.全排列_leetcode


代码如下

//递归解法
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if(nums.length==1){
result.add(Arrays.asList(nums[0]));
}
for (int i = 0; i < nums.length; i++) {
int[] restNums = getRestNums(nums, i);
List<List<Integer>> list = permute(restNums);
for (List<Integer> list1 : list) {
List<Integer> list2 = new ArrayList<>(list1);
list2.add(nums[i]);
result.add(list2);
}
}
return result;
}

private static int[] getRestNums(int[] nums, int i) {
final int[] restNums = new int[nums.length - 1];
for (int n = 0; n < i; n++) {
restNums[n] = nums[n];
}
for (int n = i + 1; n < nums.length; n++) {
restNums[n - 1] = nums[n];
}
return restNums;
}