[LeetCode] 90. Subsets II Java

Posted BrookLearnData

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 90. Subsets II Java相关的知识,希望对你有一定的参考价值。

题目:

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

Note: 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],
  []
]

题意及分析:和subsets类似,都是使用回溯的方法求解,不过需要跳过重复的,在剩余的数组中如果当前数字等于前面数字跳过即可。

代码:

public class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
		List<List<Integer>> result=new ArrayList<>();
		List<Integer> list=new ArrayList<>();
		Arrays.sort(nums);
		backtracking(result, nums, list, 0);
		return result;
    }
	
	public void backtracking(List<List<Integer>> result,int nums[],List<Integer> list,int start) {
		result.add(new ArrayList<>(list));
		for(int i=start;i<nums.length;i++){
			if(i>start&&nums[i]==nums[i-1]) continue;    //跳过重复的
			list.add(nums[i]);
			backtracking(result, nums, list, i+1);
			list.remove(list.size()-1);
			
		}
	}
}

 

  

 


以上是关于[LeetCode] 90. Subsets II Java的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 90. Subsets II

Leetcode 90. Subsets II

[leetcode-90-Subsets II]

Leetcode 90: Subsets II

Leetcode 90. Subsets II

LeetCode 90. Subsets II