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

[解题思路]
这个就是排列组合中的排列问题。递归如下逻辑:
Func Generate
对于输入字符串s的每一位字符
        选取该字符到子集合中,并输出
        如果,当前字符不是最后一位字符
                 递归调用Generate,处理下一位字符

[Leetcode]-- Subsets
public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        Arrays.sort(S);
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> list = new ArrayList<Integer>();
        generate(result, list, S, 0, S.length);
        return result;
    }
    
    
    public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] S, int depth, int length){
        result.add(list);
        if(depth == length) return;
        for(int i = depth; i< length; i++){
            ArrayList<Integer> tmp = new ArrayList<Integer>();
            tmp.addAll(list);
            tmp.add(S[i]);
            generate(result, tmp, S, i+1, length);
        }
    }
}
[Leetcode]-- Subsets

[Leetcode]-- Subsets

上一篇:LeetCode: Permutation I & II


下一篇:[Leetcode]-- Reverse Integer