LeetCode—subsets(子集dfs)—java

题目描述

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> subsets(int[] S) {
        ArrayList> res = new ArrayList>();
        if(S==null||S.length==0){
            return res;
        }
        ArrayList list = new ArrayList();
        Arrays.sort(S);
        res.add(new ArrayList());
        dfs(S,0,list,res);
        return res;
    }
    public static void dfs(int[] S,int start,ArrayList list,ArrayList> res){
        for(int i=start;i(list));
            dfs(S,i+1,list,res);
            list.remove(list.size()-1);
        }
    }
}

你可能感兴趣的:(dfs,LeetCode,数组,牛客,Java,在线编程)