Leetcode练习: Subset
题目:
Given a set of distinct integers, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
思路一:迭代法
这种方法的基本思路,是首先复制上一轮生成的结果数组,然后从原始数组中取出一个新的元素,插入到复制生成的数组元素中
代码:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums)
{
int length = (int) nums.size();
vector<vector<int>> res(1);
if( length == 0)
return res;
std::sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i)
{
int j = (int)res.size();
while( --j >= 0 )
{
res.push_back(res[j]); //Copy the last elements vector in res
res.back().push_back(nums[i]); // Insert the new element in nums
}
}
return res;
}
};