/**
* 46.全排列<br/>
* https://leetcode-cn.com/problems/permutations/<br>
* @author wuwang
*
*/
public class p46 {
List<List<Integer>> result = new LinkedList<>();
int[] nums;
int length;
public List<List<Integer>> permute(int[] nums) {
this.nums = nums;
length = nums.length;
dfs(0);
return result;
}
// 1 2 3
// 1 3 2
public void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public void dfs(int begin) {
if (begin == nums.length) {
result.add(toArray(nums));
} else {
for (int i = begin; i < nums.length; ++i) {
swap(nums, i, begin);// 这里的交换非常精妙
dfs(begin + 1);
swap(nums, i, begin);// 还原
}
}
}
public List<Integer> toArray(int... args) {
LinkedList<Integer> arr = new LinkedList<Integer>();
for (int i : args) {
arr.add(i);
}
return arr;
}
}