46. 全排列
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Code(Java)
class Solution {
private List<List<Integer>> lists = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
Integer[] num = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
num[i] = nums[i];
}
fun(num, 0);
return lists;
}
private void fun(Integer[] num, int h) {
// 如果到根节点,记录数组到List中
if (h == num.length) {
lists.add(new ArrayList<Integer>(num.length) {
{
for (Integer integer : num) {
this.add(integer);
}
}
});
return;
} else {
fun(num, h + 1);
for (int i = h + 1; i < num.length; i++) {
//交换 num数组中 i 位置 和 h 位置
swap(num, i, h);
//下一步递归
fun(num, h + 1);
//因为刚才交换过了,下次循环前得交换回来
swap(num, i, h);
}
}
}
private void swap(Integer[] num, int index1, int index2) {
Integer e = num[index1];
num[index1] = num[index2];
num[index2] = e;
}
}