Subsets, Leetcode 解题笔记

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问题,但是为了防止重复,要注意记录每次传入的index值是当前整数的下一个。

public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        Arrays.sort(S);
        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){
            return;
        }
        for(int i = index; i < S.length; i++){
            sol.add(S[i]);
            ret.add(new ArrayList<Integer>(sol));
            dfs(ret, sol, S, i + 1);
            sol.remove(sol.size()-1);
        }
    }
}
Advertisements

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