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:

[
  [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);
        }
    }
}



你可能感兴趣的:(LeetCode,DFS,回溯,Subsets)