Topic
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
- Elements in a subset must is 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], [up ], []]
Resolution
See this topic, I immediately think of "leetcode" combinations problem solving report and "Leetcode" subsets problem solving report.
Test instructions: given an array, the number in the array is duplicated, requiring all subsets .
The idea is still backtracking . I follow the idea of the above problem, and retrace the length as a subset of 0~n. And to judge the subset of repetitions in the backtracking process .
public class Solution {list<list<integer>> ans = new arraylist<list<integer>> (); int[] num = null; Public list<list<integer>> subsetswithdup (int[] num) {this.num = num; Sort first! Arrays.sort (num); Add the subsets of length from 0 to num.length by tracking. for (int i = 0; I <= num.length; i++) {Backtracking (new arraylist<integer> (), 0, I); } return ans; } public void backtracking (list<integer> cur, int. from, int cnt) {if (cur.size () = = cnt) { Find if Cur is in the result. Boolean hassame = false; int k = Ans.size ()-1; while (k >= 0 && ans.get (k). Size () = = cnt) {list<integer> last = Ans.get (k); int i = 0; for (; i < cnt; i++) {if (Last.get (i)! = Cur.get (i)) { Break }} if (i = = cnt) {Hassame = true; Break } k--; }//If cur is isn't the same as last subset, add it to the result set. if (!hassame) {list<integer> List = new arraylist<integer> (cur); Ans.add (list); }} else {//Go on back tracking. for (int i = from; i < num.length; i++) {Cur.add (num[i]); Backtracking (cur, i + 1, CNT); Cur.remove (New Integer (Num[i])); } } }}
"Leetcode" subsets II Problem solving report