Subsets, Leetcode 解题笔记

Given a set of distinct integers, S, return all possible subsets.

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:



public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        dfs(ret, sol, S, 0);
        //add empty set
        ret.add(new ArrayList<Integer>());
        return ret;
    public void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int[] S, int index){
        if(index == S.length){
        for(int i = index; i < S.length; i++){
            ret.add(new ArrayList<Integer>(sol));
            dfs(ret, sol, S, i + 1);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s