一、非递减子序列
力扣第491题
该题新加入 set 集合用来去重,判断当前层是否有重复元素
java
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> sequence = new ArrayList<>();
int count = 0;
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return result;
}
public void backtracking(int[] nums, int index) {
Set<Integer> set = new HashSet<>();
if(index == nums.length) return;
for(int i = index; i < nums.length; i++) {
if(!set.add(nums[i])) {
continue;
}
if(count != 0 && nums[i] < sequence.get(sequence.size() - 1)) {
continue;
}
sequence.add(nums[i]);
count++;
if(count >= 2) {
result.add( new ArrayList(sequence));
}
backtracking(nums, i + 1);
sequence.remove(sequence.size() - 1);
count--;
}
}
}
时间复杂度:O(n*)
空间复杂度:O(n)
二、全排列
力扣第46题
利用数组去掉已经选出来的元素
java
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int[] used = new int[21];
public List<List<Integer>> permute(int[] nums) {
backtracking(nums);
return result;
}
public void backtracking(int[] nums) {
if(path.size() == nums.length) {
result.add(new ArrayList(path));
return;
}
for(int i = 0; i < nums.length; i++) {
if(used[nums[i] + 10] == 1) {
continue;
}
used[nums[i] + 10] = 1;
path.add(nums[i]);
backtracking(nums);
path.remove(path.size() - 1);
used[nums[i] + 10] = 0;
}
}
}
时间复杂度:O(n!)
空间复杂度:O(n)
三、全排列 II
力扣第47题
java
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int[] used = new int[21];
public List<List<Integer>> permute(int[] nums) {
backtracking(nums);
return result;
}
public void backtracking(int[] nums) {
if(path.size() == nums.length) {
result.add(new ArrayList(path));
return;
}
for(int i = 0; i < nums.length; i++) {
if(used[nums[i] + 10] == 1) {
continue;
}
used[nums[i] + 10] = 1;
path.add(nums[i]);
backtracking(nums);
path.remove(path.size() - 1);
used[nums[i] + 10] = 0;
}
}
}
时间复杂度:O(n! * n)
空间复杂度:O(n)