• Java for LeetCode 090 Subsets II


    Given a collection of integers that might contain duplicates, nums, return all possible subsets.

    Note:

    • Elements in a subset must be in non-descending order.
    • The solution set must not contain duplicate subsets.

    For example,
    If nums = [1,2,2], a solution is:

    [
      [2],
      [1],
      [1,2,2],
      [2,2],
      [1,2],
      []
    ]
    

    解题思路一:

    偷懒做法,将Java for LeetCode 078 Subsets中的List换为Set即可通过测试,JAVA实现如下:

    public List<List<Integer>> subsetsWithDup(int[] nums) {
    	    Set<List<Integer>> list = new HashSet<List<Integer>>();
    	    list.add(new ArrayList<Integer>());
    	    Arrays.sort(nums);
    	    for(int i=1;i<=nums.length;i++)
    	        dfs(list, nums.length, i, 0,nums,-1);
    	    return new ArrayList(list);
    	}
    	 
    	static List<Integer> alist = new ArrayList<Integer>();
    	 
    	static void dfs(Set<List<Integer>> list, int n, int k, int depth,int[] nums,int last) {
    	    if (depth >= k) {
    	        list.add(new ArrayList<Integer>(alist));
    	        return;
    	    }
    	    for (int i = last+1; i <= n-k+depth; i++) {
    	        alist.add(nums[i]);
    	        dfs(list, n, k, depth + 1,nums,i);
    	        alist.remove(alist.size() - 1);
    	    }
    	}
    

     解题思路二:

    思路一其实用到了Java for LeetCode 077 CombinationsJava for LeetCode 078 Subsets的结论,使用set每次添加元素都需要查询一遍,会增加额外的时间开销,我们可以有一个不使用Set的解法,JAVA实现如下:

    	public List<List<Integer>> subsetsWithDup(int[] S) {
    		List<List<Integer>> res = new ArrayList<List<Integer>>();
    		List<Integer> cur = new ArrayList<Integer>();
    		Arrays.sort(S);
    		dfs(0, res, cur, S);
    		return res;
    	}
    
    	private void dfs(int dep, List<List<Integer>> res, List<Integer> cur,
    			int[] S) {
    		if (dep == S.length) {
    			res.add(new ArrayList<Integer>(cur));
    			return;
    		}
    		int upper = dep;
    		while (upper >= 0 && upper < S.length - 1 && S[upper] == S[upper + 1])
    			upper++;
    		dfs(upper + 1, res, cur, S);
    		for (int i = dep; i <= upper; i++) {
    			cur.add(new Integer(S[dep]));
    			dfs(upper + 1, res, cur, S);
    		}
    		for (int i = dep; i <= upper; i++)
    			cur.remove(cur.size() - 1);
    	}
    
  • 相关阅读:
    如何用Matplotlib绘制三元函数
    总结一下在新工作中都学到了什么?
    Debian MySQL 卸载和安装 PHP安装
    Sphinx的配置和使用
    Python的多继承
    任务分配准则
    Python解析XMl
    什么是序列化,Python中json的load,loads,dump,dumps和pickle的load,loads,dump,dumps的区别
    程序文件路径和目录的操作之BASEDIR目录获取
    模块和包
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4516099.html
Copyright © 2020-2023  润新知