LeetCode 74 Subsets
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:
すべてが遡及しているのを見て、遡及はDFSで、DFSは現場の回復に注意します.
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で、DFSは現場の回復に注意します.
public class Solution {
public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> tmp = new ArrayList<Integer>();
//
Arrays.sort(S);
//
res.add(tmp);
//dfs
dfs(res, tmp, S, 0);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> tmp, int[] S, int pos){
for(int i=pos; i<S.length; i++){
tmp.add(S[i]);
res.add(new ArrayList<Integer>(tmp));
dfs(res, tmp, S, i+1);
//
tmp.remove(tmp.size()-1);
}
}
}