题目描述:
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
题目大意:给一个数组,把这个数组的所有子数组找出来。
思路:跟之前做的一个题非常像46. Permutations(当时的解题报告),只不过这次的长度会变化,修改一下上次的代码就可以了。
c++代码:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> arr;
for (int i = 0; i <= nums.size(); i++)
{
myFunc(i, arr, nums, 0);
}
return ans;
}
void myFunc(int length, vector<int> arr, vector<int>& nums, int pos)
{
if (length == 0)
{
ans.push_back(arr);
return;
}
for (int i = pos; i < nums.size(); i++)
{
arr.push_back(nums[i]);
myFunc(length - 1, arr, nums, i + 1);
arr.pop_back();
}
}
private:
vector<vector<int>> ans;
};