题目描述:
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],
[]
]
思路解析:
- 新加入一个字符,就可以把list保存到res中,然后回溯
- 注意保持序列的顺序,还要加上[]
- 参考:https://www.cnblogs.com/springfor/p/3879830.html
代码:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(S==null||S.length==0){
return res;
}
ArrayList<Integer> list = new ArrayList<Integer>();
Arrays.sort(S);
res.add(new ArrayList<Integer>());
dfs(S,0,list,res);
return res;
}
public static void dfs(int[] S,int start,ArrayList<Integer> list,ArrayList<ArrayList<Integer>> res){
for(int i=start;i<S.length;i++){
list.add(S[i]);
res.add(new ArrayList<Integer>(list));
dfs(S,i+1,list,res);
list.remove(list.size()-1);
}
}
}