LeeCode打卡第三十四天

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);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值