title :
Given a set of distinct integers, 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,3] , a solution is:
[ 3], [1], [2], [1,3], [+] , [2,3], [up ], []]
The following:
One idea is to apply the method of combination, in fact, combination that the problem is to ask for different n under the subset, here is actually asking for a set.
For example K=3,n=1, the method of combination the problem to obtain the set is [[1], [2], [3]];
K=3, n=2, uses the method of combination that problem to obtain the set is [[1, 2], [1, 3], [2, 3]]
K=3, n=3, using the method of combination that problem to find the set is [[[+]]
So the above 3 sets plus an empty set are not
[ 3], [1], [2], [1,3], [+] , [2,3], [up ], []]
Do you?
Just add a loop to the outside of the combination.
The code is as follows:
1 Public Static voidDfsint[] S,intStartintLen, arraylist<integer> item,arraylist<arraylist<integer>>Res) {2 if(item.size () = =Len) {3Res.add (NewArraylist<integer>(item));4 return;5 }6 for(intI=start; i<s.length;i++){7 Item.add (S[i]);8DFS (S, i+1, Len, item, RES);9Item.remove (Item.size ()-1);Ten } One A } - - Public Staticarraylist<arraylist<integer>> Subsets (int[] S) { thearraylist<arraylist<integer>> res =NewArraylist<arraylist<integer>> (); -arraylist<integer> item =NewArraylist<integer>(); - if(s.length==0| | s==NULL) - returnRes; + - Arrays.sort (S); + for(intlen = 1; Len<= s.length; len++) ADFS (s,0, len,item,res); at -Res.add (NewArraylist<integer>()); - - returnRes; -}
reference:http://blog.csdn.net/worldwindjp/article/details/23300545
The bottom is another very refined algorithm.
1 Public Static voidDfsint[] S,intStart, arraylist<integer> item,arraylist<arraylist<integer>>Res) {2 for(intI=start; i<s.length;i++){3 Item.add (S[i]);4Res.add (NewArraylist<integer>(item));5DFS (s,i+1, item,res);6Item.remove (Item.size ()-1);7 }8 9 }Ten One Public Staticarraylist<arraylist<integer>> Subsets (int[] S) { Aarraylist<arraylist<integer>> res =NewArraylist<arraylist<integer>> (); -arraylist<integer> item =NewArraylist<integer>(); - if(s.length==0| | s==NULL) the returnRes; - - Arrays.sort (S); -DFS (s,0, item,res); +Res.add (NewArraylist<integer>()); - + returnRes; A}
reference:http://blog.csdn.net/u011095253/article/details/9158397
Http://www.cnblogs.com/springfor/p/3879830.html
[*?] Subset