Subsets II

来源:互联网 发布:java http编程实例 编辑:程序博客网 时间:2024/05/21 07:50

Given a collection of integers that might contain duplicates, S, 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 S = [1,2,2], a solution is:

[  [2],  [1],  [1,2,2],  [2,2],  [1,2],  []]
这次的方法看起来和写起来都要更直观一些。

public class Solution {    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {ArrayList<ArrayList<Integer>> res = new ArrayList<>();if (num.length == 0) {return res;}ArrayList<Integer> rcd = new ArrayList<>();Arrays.sort(num);helper(res, rcd, 0, num);return res;    }private void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> rcd, int pos, int[] num){int n = num.length;if (pos == n) {res.add(rcd);return;}int endPos = pos;for (int i = pos + 1; i < n; i++) {if (num[i] == num[i - 1]) {endPos = i;}else{break;}}ArrayList<Integer> without = new ArrayList<>(rcd);helper(res, without, endPos + 1, num);for (int i = pos; i <= endPos; i++) {rcd.add(num[i]);ArrayList<Integer> nextRcd = new ArrayList<>(rcd);helper(res, nextRcd, endPos + 1, num);}}}




0 0
原创粉丝点击