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],
[]
]

这道题简单,直接recursion即可。

public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        Arrays.sort(S);
        return subsetsIndex(S, 0);
    }
    
    public ArrayList<ArrayList<Integer>> subsetsIndex(int [] S, int i)
    {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if (i == S.length)
        {
            ArrayList<Integer> temp = new ArrayList<Integer>();
            res.add(temp);
            return res;
        }
        for (ArrayList<Integer> l : subsetsIndex(S, i+1))
        {
            res.add(l);
            ArrayList<Integer> temp = new ArrayList<Integer>(l);
            l.add(0,S[i]);
            res.add(temp);
        }
        return res;
    }
}

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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