Description:
Given a set of distinct integers, return all possible subsets.
Notice
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Example:
If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [ ] ]
Link:
http://www.lintcode.com/en/problem/subsets/
解题方法:
DFS求解,注意notice里面的条件不能忽略。
Tips:
当nums为NULL时,依然有子集NULL
完整代码:
vector<vector<int> > subsets(vector<int> &nums) { vector<vector<int> > result; vector<int> temp; if(nums.size() == 0) { result.push_back(temp); //当nums为NULL时,依然有子集NULL return result; } sort(nums.begin(), nums.end()); helper(nums, result, temp,0); return result; } void helper(vector<int> &nums, vector<vector<int> > &result, vector<int> &temp, int start) { result.push_back(temp); for(int i = start; i < nums.size(); i++) { temp.push_back(nums[i]); helper(nums, result, temp, i+1); temp.pop_back(); } return; }