题目:
Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
链接: http://leetcode.com/problems/subsets/
题解:
求数组子数组。先把数组排序,之后就可以使用DFS,维护一个递增的position,递归后要backtracking。
Time Complexity - O(n * 2n), Space Complexity - O(n)
public class Solution { public ArrayList<ArrayList<Integer>> subsets(int[] S) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(S == null || S.length == 0) return result; ArrayList<Integer> list = new ArrayList<Integer>(); Arrays.sort(S); helper(result, list, S, 0); return result; } private void helper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] S, int pos){ result.add(new ArrayList<Integer>(list)); for(int i = pos; i < S.length; i ++){ list.add(S[i]); helper(result, list, S, ++pos); list.remove(list.size() - 1); } } }
测试:
Reference:
http://www.cnblogs.com/springfor/p/3879830.html
http://www.cnblogs.com/zhuli19901106/p/3492515.html
http://www.1point3acres.com/bbs/thread-117602-1-1.html