其他分享
首页 > 其他分享> > Leetcode78/90/491之回溯中的子集问题

Leetcode78/90/491之回溯中的子集问题

作者:互联网

回溯之子集问题

Leetcode78-子集

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

    private void dfs(int[] nums, int begin) {
        res.add(new ArrayList<>(path));
        for (int i=begin; i<nums.length; i++) {
            path.add(nums[i]);
            dfs(nums, i+1);
            path.remove(path.size()-1);
        }
    }

Leetcode90-子集二

    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        Arrays.sort(nums);
        dfs(nums, 0);
        return res;
    }
       private void dfs(int[] nums, int begin) {
        res.add(new ArrayList<>(path));
        for (int i=begin; i<nums.length; i++) {
            if(i>0 && i!=begin && nums[i]==nums[i-1]){
                continue;
            }
            path.add(nums[i]);
            dfs(nums, i+1);
            path.remove(path.size()-1);
        }
    }

Leetcode491-递增子序列

public class L491 {
    LinkedList<List<Integer>> res=new LinkedList<>();
    LinkedList<Integer> integers=new LinkedList<>();
    Set<Integer> set = new HashSet<Integer>();
    public List<List<Integer>> findSubsequences(int[] nums) {
        find(nums,0);
        return res;
    }

//    public void find(int[] nums,int startIndex){
//        if(integers.size()>1){
//            if(!res.contains(integers)){//去重
//                res.add(new ArrayList<>(integers));
//            }
//        }
//        for(int i=startIndex;i<nums.length;i++){
//            if(!integers.isEmpty() && nums[i]<integers.getLast()){
//                continue;
//            }
//            integers.add(nums[i]);
//            find(nums,i+1);
//            integers.removeLast();
//        }
//    }

    public void find(int[] nums,int startIndex){
        if(integers.size()>1){
            res.add(new ArrayList<>(integers));
        }
        Set set=new HashSet<Integer>();//注意在这里new 这样每次深度递归时都是新的set
        for(int i=startIndex;i<nums.length;i++){
            if(!integers.isEmpty() && nums[i]<integers.getLast() || set.contains(nums[i])){
                continue;
            }
            set.add(nums[i]);
            integers.add(nums[i]);
            find(nums,i+1);
            integers.removeLast();
        }
    }

    public static void main(String[] args) {
        int[] test=new int[]{4,6,7,7,7};
        L491 l491 = new L491();
        List<List<Integer>> subsequences = l491.findSubsequences(test);
        for (List<Integer> subsequence : subsequences) {
            for (Integer integer : subsequence) {
                System.out.print(integer);
            }
            System.out.println();
        }
    }
}

标签:nums,int,res,Leetcode78,子集,ArrayList,new,90,491
来源: https://www.cnblogs.com/fao99/p/16111677.html