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], [] ]
https://oj.leetcode.com/problems/subsets/
思路:递归构造,每一层递归都选择填或者不填s[cur]的操作。
import java.util.ArrayList; import java.util.Arrays; public class Solution { public ArrayList<ArrayList<Integer>> subsets(int[] S) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tmp = new ArrayList<Integer>(); Arrays.sort(S); subsetsHelper(res, tmp, S, 0); return res; } private void subsetsHelper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] s, int cur) { if (cur == s.length) { res.add(new ArrayList<Integer>(tmp)); return; } // not fill subsetsHelper(res, tmp, s, cur + 1); // fill tmp.add(s[cur]); subsetsHelper(res, tmp, s, cur + 1); tmp.remove(tmp.size() - 1); } public static void main(String[] args) { System.out.println(new Solution().subsets(new int[] { 4, 1, 0 })); } }
第二遍记录:
子集一直不是很熟,重新复习了下。
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Solution { public List<List<Integer>> subsets(int[] S) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (S == null || S.length == 0) return res; Arrays.sort(S); List<Integer> tmp = new ArrayList<Integer>(); subsetsHelper(res, tmp, S, 0); return res; } private void subsetsHelper(List<List<Integer>> res, List<Integer> tmp, int[] S, int cur) { if (cur == S.length) { res.add(new ArrayList<Integer>(tmp)); return; } else { subsetsHelper(res, tmp, S, cur + 1); tmp.add(S[cur]); subsetsHelper(res, tmp, S, cur + 1); tmp.remove(tmp.size() - 1); } } public static void main(String[] args) { System.out.println(new Solution().subsets(new int[] { 4, 1, 0 })); } }
C语言的 位向量法
#include<cstdio> #include<cstdlib> #include<ctime> const int maxn = 50; void print_subset(int n, int A[], int B[], int cur) { if (cur == n) { for (int i = 0; i < n; i++) if (B[i]) printf("%d ", A[i]); printf(" "); return; } B[cur] = 1; //choose element cur print_subset(n, A, B, cur + 1); B[cur] = 0; //not to choose element cur print_subset(n, A, B, cur + 1); } int main() { int n; int B[maxn] = { 0 }; int A[] = { 1, 3, 5 }; n=sizeof(A)/sizeof(int); print_subset(n,A, B, 0); return 0; }
第四遍记录:
画递归调用图。
public class Solution { public List<List<Integer>> subsets(int[] s) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> tmp = new ArrayList<Integer>(); Arrays.sort(s); subsetsHelper(res,tmp,s,0); return res; } private void subsetsHelper(List<List<Integer>> res, List<Integer> tmp, int[] s,int start){ res.add(new ArrayList<Integer>(tmp)); for(int i=start;i<s.length;i++){ if(i==start||s[i]!=s[i-1]){ tmp.add(s[i]); subsetsHelper(res,tmp,s,i+1); tmp.remove(tmp.size()-1); } } } }