LeetCode——Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.

  • Example:
    Input: [1,2,2]
    Output:
    [
    [2],
    [1],
    [1,2,2],
    [2,2],
    [1,2],
    []
    ]

解法——递归

要注意跳过相同的数字不加入其中避免重复

public List<List<Integer>> subsetsWithDup(int[] nums) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		Arrays.sort(nums);
        dfs(res, new ArrayList<Integer>(), nums, 0);
		return res;
	}

	private void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] nums, int start) {
		// TODO Auto-generated method stub
		res.add(new ArrayList<Integer>(list));
		for(int i=start;i<nums.length;i++)
		{
			list.add(nums[i]);
			dfs(res,list,nums,i+1);
			list.remove(list.size()-1);
            while (i + 1 < nums.length && nums[i] == nums[i + 1]) 
                ++i;            

		}
	}

Runtime: 1 ms, faster than 100.00% of Java online submissions for Subsets II.
Memory Usage: 38.4 MB, less than 44.79% of Java online submissions for Subsets II.

解法二——迭代

参考

public List<List<Integer>> subsetsWithDup(int[] nums){
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		res.add(new ArrayList<Integer>());
		if(nums==null||nums.length==0)
			return res;
		Arrays.sort(nums);
		int size=1,last=nums[0];
		for(int i=0;i<nums.length;i++){
			if(last!=nums[i])
			{
				size=res.size();
				last=nums[i];
			}
			int newsize=res.size();
			for(int j=newsize-size;j<newsize;j++)
			{
				List<Integer> list=new ArrayList<Integer>(res.get(j));
				list.add(nums[i]);
				res.add(list);
			}
		}
		return res;
	}

Runtime: 1 ms, faster than 100.00% of Java online submissions for Subsets II.
Memory Usage: 38.2 MB, less than 47.32% of Java online submissions for Subsets II.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值