【Leetcode】【Medium】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], [] ]
解题思路:
题目要求返回值要从大到小排列,因此先对序列S排序o(nlogn);
假设S为abcd...,然后遍历S中每个数,
对a,返回集合[ [ ], [a] ]
对b,返回集合{ [ ], [a], [b], [a, b] }
由此看出,每出现一个新值,就是保存返回集合中原有数组不变,并在每个原有数组后加上新值,组合成新数组,添加到返回集合的后面;
代码:
1 class Solution { 2 public: 3 vector<vector<int> > subsets(vector<int> &S) { 4 sort(S.begin(), S.end()); 5 vector<vector<int> > ret; 6 ret.push_back(vector<int> ()); 7 8 for (int i = 0; i < S.size(); ++i) { 9 int pre_size = ret.size(); 10 for (int j = 0; j < pre_size; ++j) { 11 vector<int> new_item(ret[j]); 12 new_item.push_back(S[i]); 13 ret.push_back(new_item); 14 } 15 } 16 return ret; 17 } 18 };
附录:
C++ vector 浅复制、深复制