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

思想:集合求解找递归关系。

注意事项: 在解决java问题时,要留意对引用的操作。

java代码:
  1. public ArrayList<ArrayList<Integer>> subsets(int[] S) {
  2. int len = S.length;
  3. ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
  4. ArrayList<Integer> cur = new ArrayList<Integer>();
  5. res.add(new ArrayList<Integer>(cur));
  6. if(len == 0) return res;
  7. Arrays.sort(S);//保证结果递增
  8. for(int i=0;i<len;i++) {
  9. int rlen = res.size();
  10. for(int j=0;j<rlen;j++) {
  11. ArrayList<Integer> tmp = new ArrayList<Integer>(res.get(j));  //如何直接获取,则操作的就是原引用
  12. tmp.add(S[i]);
  13. res.add(tmp);
  14. }
  15. }
  16. return res;
  17. }

C++代码: 更简洁,不存在引用的问题

  1. vector<vector<int> > subsets(vector<int> &S) {
  2. int N=S.size();
  3. sort(S.begin(),S.end());
  4. vector<vector<int> > res(1);
  5. for(int i=0;i<N;i++) {
  6. int j=res.size();
  7. while(j-- > 0) { // j=j-1 j>0
  8. res.push_back(res[j]);
  9. res.back().push_back(S[i]);
  10. }
  11. }
  12. return res;
  13. }

C++代码: 用bit求解

  1. vector<vector<int> > subsets(vector<int> &S) {
  2. int N=S.size();
  3. sort(S.begin(),S.end());
  4. vector<int> tmp;
  5. for(int i=0;i<pow(2,N);i++) {
  6. tmp.clear();
  7. for(int j=0;j<N;j++) {
  8. int exist = (i>>j) & 1;
  9. if(exist) {
  10. tmp.push_back(S[j]);
  11. }
  12. }
  13. res.push_back(tmp);
  14. }
  15. return res;
  16. }

C++: 用dfs求解,把tmp作为中间变量,不需要&

  1. vector<vector<int> > res;
  2. void subsetsHelper(vector<int> &S,vector<int> tmp,int cnt) {
  3. if(cnt == S.size()) {
  4. res.push_back(tmp);
  5. return;
  6. }
  7. subsetsHelper(S,tmp,cnt+1); // 0
  8. tmp.push_back(S[cnt]);
  9. subsetsHelper(S,tmp,cnt+1); //1,如果不行直接退出,tmp又恢复上一个值,并没有对上一个值进行改变
  10. }
  11. vector<vector<int> > subsets(vector<int> &S) {
  12. sort(S.begin(),S.end());
  13. vector<int> tmp;
  14. subsetsHelper(S,tmp,0);
  15. return res;
  16. }
posted @ 2014-07-20 23:40  purejade  阅读(121)  评论(0编辑  收藏  举报