【LeetCode】78. Subsets 解题报告(Python & C++)

901 篇文章 204 订阅

题目地址:https://leetcode.com/problems/subsets/description/

题目描述

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],
  []
]

题目大意

给了输入数组,返回这个数组的所有能够成的子集。

解题方法

递归

先要找出一个数组全部的子集,可以从题目给的实例中找出答案。我们发现这个实例就是从数组中的每个数字都有不用两个状态。

因此可以写两个递归,分别表示用和不用当前元素的情况下,后续的递归结果。当index到达数组结尾的时候,就把路径path放入结果中就好了。

C++代码如下:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        dfs(res, {}, nums, 0);
        return res;
    }
    void dfs(vector<vector<int>>& res, vector<int> path, vector<int>& nums, int index) {
        if (index >= nums.size()) {
            res.push_back(path);
            return;
        }
        dfs(res, path, nums, index + 1);
        path.push_back(nums[index]);
        dfs(res, path, nums, index + 1);
    }
};

上面的递归解法是当前元素用或者不用两种状态,另外一种递归解法是当前的元素一定使用,然后递归把后面的元素是否选择一些放入当前元素后面。

递归最重要的是明白递归函数的意义。下面代码的dfs()函数,就是在当前index元素使用的情况下,从nums的index后面抽取0个或者全部数字放入path的后面,注意这个for循环,意义是当前元素如果使用,后面的那个元素从哪里开始,也就决定了后面的数字选择多少个。

python代码如下:

class Solution(object):
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        self.dfs(nums, 0, res, [])
        return res
    
    def dfs(self, nums, index, res, path):
        res.append(path)
        for i in xrange(index, len(nums)):
            self.dfs(nums, i + 1, res, path + [nums[i]])

回溯法

C++解法,同样的也是回溯法。

和上面的python递归解法有点类似,不过称其为回溯法是因为path是传的引用,这样path需要我们自己维护,添加元素弹出元素操作分别在递归函数的前后执行,从而达到了当前元素使用完成之后,进行回溯的效果。

C++代码如下:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> path;
        helper(nums, res, path, 0);
        return res;
    }
    void helper(const vector<int>& nums, vector<vector<int>>& res, vector<int>& path, int start) {
        res.push_back(path);
        for (int i = start; i < nums.size(); i ++) {
            path.push_back(nums[i]);
            helper(nums, res, path, i + 1);
            path.pop_back();
        }
    }
};

日期

2018 年 2 月 24 日
2018 年 12 月 20 日 —— 感冒害的我睡不着
2019 年 9 月 25 日 —— 做梦都在秋招,这个秋天有毒

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!对于LeetCode上的问题994.腐烂的橘子,你可以使用Python来解决。下面是一个示例代码: ```python from collections import deque def orangesRotting(grid): # 记录网格的行数和列数 row, col = len(grid), len(grid[0]) # 定义四个方向:上、下、左、右 directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] # 使用队列来保存腐烂的橘子的位置 queue = deque() # 记录新鲜橘子的数量 fresh_count = 0 # 遍历整个网格,初始化队列和新鲜橘子的数量 for i in range(row): for j in range(col): if grid[i][j] == 2: # 腐烂的橘子 queue.append((i, j)) elif grid[i][j] == 1: # 新鲜橘子 fresh_count += 1 # 如果新鲜橘子的数量为0,直接返回0 if fresh_count == 0: return 0 # 初始化分钟数 minutes = 0 # 开始进行BFS,直到队列为空 while queue: # 记录当前分钟数下,队列中的元素数量 size = len(queue) # 遍历当前分钟数下的所有腐烂的橘子 for _ in range(size): x, y = queue.popleft() # 遍历四个方向 for dx, dy in directions: nx, ny = x + dx, y + dy # 判断新位置是否在网格内,并且是新鲜橘子 if 0 <= nx < row and 0 <= ny < col and grid[nx][ny] == 1: # 将新鲜橘子变为腐烂状态 grid[nx][ny] = 2 # 将新鲜橘子的位置加入队列 queue.append((nx, ny)) # 新鲜橘子的数量减1 fresh_count -= 1 # 如果当前分钟数下,没有新鲜橘子了,结束循环 if fresh_count == 0: break # 每遍历完一层,分钟数加1 minutes += 1 # 如果最后还有新鲜橘子,返回-1,否则返回分钟数 return -1 if fresh_count > 0 else minutes ``` 你可以将给定的网格作为参数传递给`orangesRotting`函数来测试它。请注意,该代码使用了BFS算法来遍历橘子,并计算腐烂的分钟数。希望能对你有所帮助!如果有任何疑问,请随时问我。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值