题目:
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
大意:
给一个数组,求数组的全排列。
思路:
使用递归,dfs求解。
参考:tuantuanls的专栏
建立一棵树:
对于第k层节点来说,就是交换固定了前面 k-1 位,然后分别 swap(k,k), swap(k, k+1) , swap(k, k+2) …
例如上图中的第三层,固定了第一位(即2),然后分别交换第1,1位,1,2位,1,3位。
代码:
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
permute(0, nums, result);
return result;
}
private void permute(int i, int[] nums, List<List<Integer>> result) {
if(i == nums.length) {
//产生一个结果,放入result中
List<Integer> temp = new ArrayList<>();
for(int j = 0; j < nums.length; j++) {
temp.add(nums[j]);
}
result.add(temp);
} else {
for(int j = i; j < nums.length; j++) {
swap(nums, j, i);
//固定前i个值,从第i+1开始往后交换
permute(i + 1, nums, result);
//在递归的同一层,再换回来,进入下一轮for循环
swap(nums, j, i);
}
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}