1. 题目

2. 思路
(1) 递归
- 终止条件是当数组元素的个数等于1时,返回只包含该元素的集合。
- f(n)与f(n-1)的关系是将f(n)多出来的元素分别插入f(n-1)集合的每一个间隙中得到新的集合。
(2) 回溯
3. 代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.permute(new int[]{
1, 2, 3}));
}
}
class Solution {
public List<List<Integer>> permute(int[] nums) {
return permute(nums, nums.length - 1);
}
private List<List<Integer>> permute(int[] nums, int right) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp;
if (right == 0) {
temp = new ArrayList<>();
temp.add(nums[0]);
res.add(temp);
return res;
}
List<List<Integer>> pre = permute(nums, right - 1);
int preRow = pre.size();
int preCol = pre.get(0).size();
for (int i = 0; i < preRow; i++) {
for (int j = 0; j <= preCol; j++) {
temp = new ArrayList<>();
for (int k = 0; k <= preCol; k++) {
if (k == j) {
temp.add(nums[right]);
}
if (k < preCol) {
temp.add(pre.get(i).get(k));
}
}
res.add(temp);
}
}
return res;
}
}
class Solution1 {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> output = new ArrayList<>();
for (int num : nums) {
output.add(num);
}
int len = nums.length;
backtrack(0, len, output, res);
return res;
}
private void backtrack(int index, int len, List<Integer> output, List<List<Integer>> res) {
if (index == len) {
res.add(new ArrayList<>(output));
}
for (int i = index; i < len; i++) {
Collections.swap(output, index, i);
backtrack(index + 1, len, output, res);
Collections.swap(output, index, i);
}
}
}