Tuesday, February 17, 2015

Subsets

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],
  []
]
------------------------------- think ----------------------------------------------
two ways to do:
1. bit manipulation
2. keep adding one more ele in the results
------------------------------- codes ----------------------------------------------
class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int>> result;
        if (S.size() > 31 || S.size() == 0) {
            return result;
        }
        sort(S.begin(), S.end());
        int cnt = 1 << S.size();
        for (int i = 0; i < cnt; i++) {
            vector<int> ele;
            for (int bit = S.size() - 1; bit >= 0; bit--) {
                int cur = 1 << bit;
                if (i & cur) {
                    ele.push_back(S[S.size() - bit - 1]);
                }
            }
            result.push_back(ele);
        }
        return result;
    }
};

----------------------------- read codes ----------------------------------------
public List<List<Integer>> subsets(int[] S) { List<List<Integer>> res = new ArrayList<List<Integer>>(); res.add(new ArrayList<Integer>()); Arrays.sort(S); for(int i = S.length - 1; i >= 0; i--){ int size = res.size() - 1; for(int j = size; j >= 0; j--){ List<Integer> newList1 = new ArrayList<>(); newList1.add(S[i]); newList1.addAll(res.get(j)); res.add(newList1); } } return res; }

No comments:

Post a Comment