LeetCode Subsets II

来源:互联网 发布:win7如何设置网络类型 编辑:程序博客网 时间:2024/05/01 17:33

Description:

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

Solution:

似乎前面有类似这种去不同子集的题目,DFS边形即可。

import java.util.*;public class Solution {List<List<Integer>> list = new ArrayList<List<Integer>>();int[] nums;int n;public List<List<Integer>> subsetsWithDup(int[] nums) {Arrays.sort(nums);this.nums = nums;this.n = nums.length;ArrayList<Integer> currentList = new ArrayList<Integer>();dfs(0, currentList);return list;}void dfs(int index, ArrayList<Integer> currentList) {if (index == n) {list.add(new ArrayList<Integer>(currentList));return;}int limit = index + 1;for (; limit < n; limit++)if (nums[limit] != nums[index])break;dfs(limit, currentList);for (int i = index; i < limit; i++) {currentList.add(nums[i]);dfs(limit, currentList);}for (int i = index; i < limit; i++)currentList.remove(currentList.size() - 1);}}


0 0