Given a set of distinct integers, 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,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
給出一個數組生成該數組所有元素的組合。
基本思路循環+dfs,生成指定元素數目(0,1,2,...array.size()個元素)的組合。
1和2的區別在於2中允許數組中出現重復的元素。所以2在dfs的時候要跳過重復的元素,例如:[1,1,2] 如果不加跳過處理的話,生成的 子集會有兩個:[1,2]。
LeetCode Subsets的AC代碼:
public class Solution { void dfs(int [] number_array, int start, int number, ArrayListLeetCode Subsets II 的AC代碼:array, ArrayList> result) { if(number==array.size()) { result.add(new ArrayList (array)); return; } for(int i=start;i subsets(int[] S) { ArrayList> result = new ArrayList>(); ArrayList array = new ArrayList (); result.add(array); if(S==null) { return result; } Arrays.sort(S); for(int i=1;i<=S.length;i++) { array.clear(); dfs(S,0,i,array,result); } return result; } }
public class Solution { void dfs(int[] number_array, int start, int number, ArrayListarray, ArrayList> result) { if(array.size()==number) { result.add(new ArrayList (array)); return; } int i = start; while(i subsetsWithDup(int[] num) { ArrayList> result = new ArrayList>(); ArrayList array = new ArrayList (); result.add(array); if(num==null) { return result; } Arrays.sort(num); for(int i=1;i<=num.length;i++) { array.clear(); dfs(num,0,i,array,result); } return result; } }