题目
Given a collection of distinct numbers, return all possible permutations.
答案
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> curr = new ArrayList<Integer>();
boolean[] used = new boolean[nums.length];
recur(nums, used, 0, curr, list);
return list;
}
private void recur(int[] nums, boolean[] used, int i, List<Integer> curr, List<List<Integer>> list) {
if(i == nums.length) {
list.add(new ArrayList<Integer>(curr));
return;
}
for(int j = 0; j < nums.length; j++) {
if(!used[j]) {
curr.add(nums[j]);
used[j] = true;
recur(nums, used, i + 1, curr, list);
used[j] = false;
curr.remove(curr.size() - 1);
}
}
}
}