Question:
Given a set of distinct integers, nums, return all possible subsets.
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], [] ]
Algorithm:
也是用二叉树的思想,不过这次不需要判断长度,每更新一次数组,就赋值给二维数组(最终结果)。如果数组长度等于nums的长度就返回。
Accepted Code:
class Solution { public: vector<vector<int>> res; vector<vector<int>> subsets(vector<int>& nums) { vector<int> cur; BFS(nums,cur,0); return res; } void BFS(vector<int>& nums,vector<int>& cur,int k) { if(cur.size()==nums.size()) { res.push_back(cur); return; } else { res.push_back(cur); for(int i=k;i<nums.size();i++) { vector<int> temp=cur; temp.push_back(nums[i]); BFS(nums,temp,i+1); } } } };
时间: 2024-10-05 19:25:17