03.子集问题

 

第78题. 子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例: 输入: nums = [1,2,3] 输出: [ [3],   [1],   [2],   [1,2,3],   [1,3],   [2,3],   [1,2],   [] ]

class Solution {

    List<List<Integer>> ans=new ArrayList<>();
    List<Integer> path=new ArrayList<>();
 
    public List<List<Integer>> subsets(int[] nums) {
       process(nums,0);
       return ans;
    }

    private void process(int[] nums,int index){

         ans.add(new ArrayList<>(path));

         if(index>=nums.length){
             return;
         }

        for(int i=index;i<nums.length;i++){
            path.add(nums[i]);
            process(nums,i+1);
            path.remove(path.size()-1);
        }

    }

  
}

  

第90题.子集II

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例: 输入: [1,2,2] 输出: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]

class Solution {
    List<List<Integer>> ans=new ArrayList<>();
    List<Integer> path=new ArrayList<>();
    boolean[] used;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
         used=new boolean[nums.length];
        process(nums,0);
        return ans;
    }

    private void process(int[] nums,int index){
        ans.add(new ArrayList<>(path));
        if(index>=nums.length){
            return;
        }
       
        for(int i=index;i<nums.length;i++){
            if(i>0 && nums[i]==nums[i-1] && !used[i-1]){
                continue;
            }
                used[i]=true;
                path.add(nums[i]);
                process(nums,i+1);
                path.remove(path.size()-1);
                used[i]=false;
             
            }
          
    }
}

 

491.递增子序列

给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。

示例:

  • 输入: [4, 6, 7, 7]
  • 输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]

说明:

  • 给定数组的长度不会超过15。
  • 数组中的整数范围是 [-100,100]。
  • 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。 
class Solution {
    List<List<Integer>>  ans=new ArrayList<>();
    List<Integer> path=new ArrayList();
    public List<List<Integer>> findSubsequences(int[] nums) {
        process(nums,0);
        return ans;
    }

    private void process(int[] nums,int index){
        if(path.size()>=2){
            ans.add(new ArrayList<>(path));
        }
        
        int[] used=new int[202];
        for(int i=index;i<nums.length;i++){
            if(!path.isEmpty() && nums[i]<path.get(path.size()-1) || used[100+nums[i]]==1){
                continue;
            }
            
                used[100+nums[i]]=1;
                path.add(nums[i]);
                process(nums,i+1);
                path.remove(path.size()-1);
            

          
        }
    }
}

  

  

posted @ 2021-12-07 22:10  sherry001  阅读(27)  评论(0编辑  收藏  举报