题解 | #集合的所有子集#
集合的所有子集
http://www.nowcoder.com/practice/c333d551eb6243e0b4d92e37a06fbfc9
import java.util.*;
public class Solution {
public static ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
ArrayList<Integer> track = new ArrayList<>();
Arrays.sort(S);
dfs(S, 0, track);
Collections.sort(res,(o1,o2)->{
return o1.size()-o2.size();
});
return res;
}
public void dfs(int[] arr, int index, ArrayList<Integer> temp){
//if(index>=arr.length) return;
res.add(new ArrayList<Integer>(temp));
for(int i=index;i<arr.length;i++){
temp.add(arr[i]);
dfs(arr,i+1,temp);
temp.remove(temp.size()-1);
}
}
}
回溯后对输出按照元素的长度排个序
