LeeCode打卡第三十四天
第一题:非递减子序列(LeeCode第491题):
给你一个整数数组 nums
,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
HashSet<List<Integer>> set = new HashSet<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return res;
}
private void backtracking(int[] nums, int startIndex){
if(temp.size() > 1){
if(!set.contains(temp)){
set.add(new ArrayList<>(temp));
res.add(new ArrayList<>(temp));
}
}
for(int i = startIndex; i < nums.length; i++){
if(temp.isEmpty() || nums[i] >= temp.get(temp.size() - 1)){
temp.add(nums[i]);
backtracking(nums, i + 1);
temp.remove(temp.size() - 1);
}
while(i + 1 < nums.length && nums[i] == nums[i + 1]) i++;
}
}
}
第二题:子集II(LeeCode第90题):
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的 子集(幂集)。解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
backtracking(nums, 0);
// res.add(new ArrayList<>());
return res;
}
private void backtracking(int[] nums, int startIndex){
res.add(new ArrayList<>(temp));
for(int i = startIndex; i < nums.length; i++){
if(i > startIndex && nums[i] == nums[i - 1]) continue;
temp.add(nums[i]);
backtracking(nums, i + 1);
temp.remove(temp.size() - 1);
}
}
}