不重复,直接这样递归就行
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
dfs(nums,0);
return res;
}
public void dfs(int[] nums,int index){
if(index==nums.length){
ArrayList<Integer> list = new ArrayList<>();
for(int num:nums) list.add(num);
res.add(list);
}
for(int i=index;i<nums.length;i++){
swap(nums,index,i);
dfs(nums,index+1);
swap(nums,index,i);
}
}
public void swap(int[] nums,int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
含重复,剪枝叶的时候,需要注意,不是简单的跳过,而是前面出现过,就要跳过。因为swap后,顺序被打乱了
public class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
dfs(nums,0);
return res;
}
public void dfs(int[] nums, int index){
if(index == nums.length){
ArrayList<Integer> list = new ArrayList<>();
for(Integer num:nums) list.add(num);
res.add(list);
return;
}
for(int i=index;i<nums.length;i++){
if(!isOk(nums,index,i)) continue;
swap(nums,index,i);
dfs(nums,index+1);
swap(nums,index,i);
}
}
public boolean isOk(int[] nums, int start, int end){
for(int j=start;j<end;j++){
if(nums[j]==nums[end]) return false;
}
return true;
}
public void swap(int[] nums,int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}