LeetCode: Subsets

思路:对于第n个元素生成的子集,其中一半来自于第n-1个元素的子集,另一半就是将A[i] 添加到第n-1个元素生成的子集。

即SubSet(n) = SubSet(n-1) ∪{A[n] + SubSet(n-1)}

code:

class Solution {
public:
    vector<vector<int> > subsets(vector<int> &S) {
        sort(S.begin(),S.end());
        vector<vector<int> >ret;
        vector<int> temp;
        ret.push_back(temp);
        for(int i = 0;i<S.size();i++){
            vector<vector<int> > tempRet = ret;
            for(int j=0;j<ret.size();j++){
                vector<int> t = ret[j];
                t.push_back(S[i]);
                tempRet.push_back(t);
            }
            ret = tempRet;
        }
        return ret;
    } 
};


你可能感兴趣的:(LeetCode: Subsets)