leetcode [78] Subsets
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],
[]
]
题目大意:
找出的集合的所有子集,集合元素并不重复
解法:
C++:
class Solution { public: void dfs(vector<int> nums,int index,vector<int>&tmp,vector<vector<int>>&res){ res.push_back(tmp); if(index==nums.size()) return; for(int i=index;i<nums.size();i++){ tmp.push_back(nums[i]); dfs(nums,i+1,tmp,res); tmp.pop_back(); } } vector<vector<int>> subsets(vector<int>& nums) { vector<int>tmp; vector<vector<int>>res; dfs(nums,0,tmp,res); return res; } };
Python:
class Solution(object): def dfs(self,nums,res,tmp,index): res.append(tmp) if index==len(nums): return for i in range(index,len(nums)): self.dfs(nums,res,tmp+[nums[i]],i+1) def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return None res=[] tmp=[] self.dfs(nums,res,tmp,0) return res