当前位置: 代码迷 >> 综合 >> Leetcode 78. Subsets (python+cpp)
  详细解决方案

Leetcode 78. Subsets (python+cpp)

热度:12   发布时间:2023-11-26 06:04:23.0

题目

在这里插入图片描述

解法:

对应combination无重复,只是添加到答案的条件不需要长度跟原数组一样罢了。关于permutation和combination,参考这里

python版本

class Solution:def subsets(self, nums: List[int]) -> List[List[int]]:def dfs(sub,level):ans.append(sub[:])if level == len(nums):returnfor i in range(level,len(nums)):sub.append(nums[i])dfs(sub,i+1)sub.pop()ans = []dfs([],0)return ans;

C++版本

class Solution {
    
public:vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> ans;vector<int> sub;dfs(nums,sub,ans,0);return ans;}void dfs(vector<int>& nums, vector<int>& sub, vector<vector<int>>& ans, int level){
    ans.push_back(sub);if(level == nums.size()){
    return ;}for(int i=level;i<nums.size();i++){
    sub.push_back(nums[i]);dfs(nums,sub,ans,i+1);sub.pop_back();}}
};