491.递增子序列
题目链接:491. 非递减子序列 - 力扣(LeetCode)
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtrack(nums, 0, new ArrayList<>());
return ans;
}
private void backtrack(int[] nums, int index, List<Integer> list) {
if(list.size() >= 2) {
ans.add(new ArrayList<>(list));
}
HashSet<Integer> set = new HashSet<>();
for(int i = index; i < nums.length; ++i) {
if(set.contains(nums[i])) {
continue;
}
if(list.size() >= 1 && list.getLast() > nums[i]) {
continue;
}else {
list.add(nums[i]);
set.add(nums[i]);
backtrack(nums, i+1, list);
list.removeLast();
}
}
}
}
46.全排列
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
backtrack(nums, new boolean[nums.length], new ArrayList<>());
return ans;
}
private void backtrack(int[] nums,boolean[] used, List<Integer> list) {
if(list.size() == nums.length) {
ans.add(new ArrayList<>(list));
}
for(int i = 0; i < nums.length; ++i) {
if(used[i]) {
continue;
}
list.add(nums[i]);
used[i] = true;
backtrack(nums, used, list);
list.removeLast();
used[i] = false;
}
}
}
47.全排列 II
题目链接:47. 全排列 II - 力扣(LeetCode)
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
backtrack(nums, new boolean[nums.length], new ArrayList<>());
return ans;
}
private void backtrack(int[] nums, boolean[] used, List<Integer> list) {
if(list.size() == nums.length) {
ans.add(new ArrayList<>(list));
return;
}
for(int i = 0; i < nums.length; ++i) {
if(used[i] || (i > 0 && !used[i-1] && nums[i] == nums[i-1])) {
continue;
}
list.add(nums[i]);
used[i] = true;
backtrack(nums, used, list);
used[i] = false;
list.removeLast();
}
}
}