
解题思路:
回溯
假设给定数组nums为1, 2, 3,首先将其转换为List<Integer>类型的output为1, 2, 3。
在backtrack方法中,初始时first为0,所以进入第一个for循环,交换output中第一个元素和自身,然后递归调用backtrack方法,此时first为1,再次进入for循环,交换output中第二个元素(即2)和自身。这样得到的output为1, 2, 3,添加到结果集中。
接着回到第一个for循环,再次交换output中第一个元素和自身,此时成为2, 1, 3,再次递归调用backtrack方法,得到的output为2, 1, 3,添加到结果集中。
依次类推,通过不断交换元素的位置和递归调用backtrack方法,可以生成所有可能的排列组合。最终得到的结果为\[1, 2, 3, 2, 1, 3, 3, 1, 2, 1, 3, 2, 2, 3, 1, 3, 2, 1],即给定数组1, 2, 3的全排列结果。
java
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> output = new ArrayList<>();
for (int num : nums) {
output.add(num);
}
int n = nums.length;
backtrack(n, output, res, 0);
return res;
}
public void backtrack(int n, List<Integer> output, List<List<Integer>> res, int first) {
if (first == n)
res.add(new ArrayList<Integer>(output));
for (int i = first; i < n; i++) {
Collections.swap(output, first, i);
backtrack(n, output, res, first + 1);
Collections.swap(output, first, i);
}
}
}