题目描述:
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], [] ]
找到所有题目所给数组的子集。
解题思路:
1)当n = 0时,只有一个空集;
2)数组有n个数字的子集是 n-1个数字的子集+n-1个数字的每个子集加上第n个数字,
知道这两点就可以用递推写出代码了。
代码:
1 class Solution { 2 public: 3 vector<vector<int>> subsets(vector<int>& nums) { 4 int n = nums.size(); 5 vector<vector<int>> ret(1); 6 if(n < 1) 7 return ret; 8 for(int i = 0; i < n; i++){ 9 int s = ret.size(); 10 for(int j = 0; j < s; j++){ 11 vector<int> t(ret[j]); 12 t.push_back(nums[i]); 13 ret.push_back(t); 14 } 15 } 16 return ret; 17 } 18 };