算法描述:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]Output:[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]
解题思路:题目要求所有可能的子集,因此首先想到回溯法求解。注意边界,以及返回问题。
vector> subsets(vector & nums) { vector > results; vector temp; backtracking(nums,results, temp, 0); return results; } void backtracking(vector & nums, vector >& results, vector & temp, int index){ if(temp.size() <= nums.size()){ results.push_back(temp); } if(temp.size()==nums.size()) return; for(int i=index; i < nums.size();i++){ temp.push_back(nums[i]); backtracking(nums, results, temp, i+1); temp.pop_back(); } }