Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
If S =
[1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
public class Solution { private List<List<Integer>> result; private List<Integer> ret; public List<List<Integer>> subsetsWithDup(int[] num) { // Backtracking problem // Firstly, sort num array result = new LinkedList<>(); ret = new LinkedList<>(); int n = num.length; Arrays.sort(num); backTracking(num, 0); // Don't miss NULL set. // Note: It must be put back of 'backTracking' function; Otherwise, it will affect '!result.contains()'. result.add(new LinkedList<Integer>()); return result; } private void backTracking(int[] num, int cnt) { if (cnt == num.length) return; else { for (int i = cnt; i < num.length; i++) { ret.add(num[i]); List<Integer> copyRet = new LinkedList<>(ret); if (!result.contains(copyRet)) result.add(copyRet); backTracking(num, i+1); ret.remove(ret.size()-1); } } } }
No comments:
Post a Comment