给定一组数(未排序), 求它们的所有组合可能.
如给定{1 2 3}, 返回:
[ [] [1] [2] [3] [1 2] [1 3] [2 3] [1 2 3] ]
算法思路:
- 对数组排序, 从小到大;
- 令 i = 0, 对已有组合v从后往前进行如下操作
- v的最后1个组合内加入第i个元素;
- 将新组合加入到v中
算法的理解可以通过一个例子来看:
给定S = {1 2 3},
v = [[]]
i = 0, j = 1, v = [[] [1]] // back().push_back(S[0])
i = 1, j = 2, v = [[] [1] | [1 2] [2]] // j = 2, add 2 new elems
i = 2, j = 4, v = [[] [1] [1 2] [2] | [2 3] [1 2 3] [1 3] [3]]
相同颜色前者为原有元素, 后者为增加后的元素.
代码:
class Solution {
public:
vector<vector<int> > subsets(vector<int> &S) {
sort(S.begin(), S.end());
vector<vector<int> > v();
for(int i = ; i < S.size(); ++i) {
int j = v.size();
while(j-- > ) {
v.push_back(v[j]);
v.back().push_back(S[i]);
}
}
return v;
}
};