回溯
class Solution {
private List<List<Integer>> ans = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
backTrace(nums, 0);
return ans;
}
private void backTrace(int[] nums, int begin) {
if (begin == nums.length) {
List<Integer> one = new LinkedList<>();
for (int num : nums) {
one.add(num);
}
ans.add(one);
}
for (int i = begin; i < nums.length; i++) {
exch(nums, i, begin);
backTrace(nums, begin + 1);
exch(nums, i, begin);
}
}
private void exch(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}