[LeetCode] Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
利用回溯法求出给定数组的所有不重复子数组。
这个题没有边界条件,所以使用直接使用回溯标准形式即可
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> tmp; int idx = 0; helper(res, tmp, nums, idx); return res; } void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& nums, int idx) { res.push_back(tmp); for (int i = idx; i < nums.size(); i++) { tmp.push_back(nums[i]); helper(res, tmp, nums, i + 1); tmp.pop_back(); } } }; // 6 ms