码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode [78] Subsets

时间:2019-04-02 21:02:57      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:obj   not   c++   oss   contain   class   res   void   nbsp   

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

leetcode [78] Subsets

标签:obj   not   c++   oss   contain   class   res   void   nbsp   

原文地址:https://www.cnblogs.com/xiaobaituyun/p/10645116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!