【leetcode】90. Subsets II【java】

来源:互联网 发布:win32多线程编程实例 编辑:程序博客网 时间:2024/05/22 00:45

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],  []]
public class Solution {    public List<List<Integer>> subsetsWithDup(int[] nums) {        //回溯法        List<List<Integer>> result = new ArrayList<List<Integer>>();        Arrays.sort(nums);        List<Integer> tmp = new ArrayList<Integer>();         backtrack(result, tmp, nums, 0);        return result;    }    private void backtrack(List<List<Integer>> result, List<Integer> tmp, int[] nums, int start){        //add前需要进行判断result中是否已经包含该元素。有可能重复。        if (!result.contains(tmp)){            result.add(new ArrayList(tmp));        }        for (int i = start; i < nums.length; i++){            tmp.add(nums[i]);            backtrack(result, tmp, nums, i + 1);            tmp.remove(tmp.size() - 1);        }    }}

0 0