问题一:46、全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
public List<List<Integer>> permute(int[] nums) {
int n = nums.length;
int[] uesd = new int[n];
backtracking(nums, uesd);
return ans;
}
void backtracking(int[] nums, int[] uesd){
if(path.size() == nums.length){
ans.add(new ArrayList<>(path));
return;
}
for(int i = 0; i < nums.length; i++){
if(uesd[i] == 1)continue;
path.add(nums[i]);
uesd[i] = 1;
backtracking(nums, uesd);
path.remove(path.size() - 1);
uesd[i] = 0;
}
}
}
问题二:47、全排列2
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
int[] used = new int[nums.length];
backtracking(nums, used);
return ans;
}
void backtracking(int[] nums, int[] used){
if(path.size() == nums.length){
ans.add(new ArrayList<Integer>(path));
return;
}
for(int i = 0; i < nums.length; i++){
if(used[i] == 1 || (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0))continue;
used[i] = 1;
path.add(nums[i]);
backtracking(nums, used);
used[i] = 0;
path.remove(path.size() - 1);
}
}
}