Datawhale LeetCode腾讯精选50——Task08

LeetCode062:不同路径

A robot is located at the top-left corner of a m x n grid
 (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. 
The robot is trying to reach the bottom-right corner of the grid 
(marked 'Finish' in the diagram below).

How many possible unique paths are there?

在这里插入图片描述
在这里插入图片描述

思路一:排列组合,根据棋盘形状,推算出向右需要走m-1步,向下需要走n-1步,而我们需要走入最后一个网格,也就是说我们要在一共能走的步数中选m-1步往右,其余向下走。等同于高中学过的排列组合。
思路二:动态规划,横列竖列只有可能有1种情况,而剩下的坐标的路径数都等于它左边和上边的值相加。
思路一和二的详细解释和代码参见Leetcode 062 不同路径 Python (动态规划)
思路三:说实话,没看明白,代码贴出来,懂得可以告诉我下。。。这段代码出自62. 不同路径–Python

class Solution(object):
    def uniquePaths(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        j=min(m-1,n-1)
        if j==0:
            return 1
        k=m+n-2
        res1=1
        res2=1
        for i in range(j):
            res1*=k-i
            res2*=j-i
        return res1/res2

LeetCode062:不同路径官方解决方案

LeetCode070:爬楼梯

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. 
In how many distinct ways can you climb to the top?

在这里插入图片描述

思路一:递归,直接递归会超时,所以可以用一个dict保存中间结果复用。
思路二:动态规划(斐波那契数列)
由于第二种思路是很常见的,所以这里放第一种的代码。这两个思路的详细解释和代码都出自leetcode 70 python 爬楼梯

# 直接使用递归会AC超时,这里使用一个dict保存中间结果复用,勉强通过
d = dict()

class Solution:
    
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        if not n:
            return 0
        if n == 1 or n == 2:
            return n
        if d.get(n):
            return d.get(n)
        res = self.climbStairs(n-1) + self.climbStairs(n-2)
        d[n] = res
        return res

LeetCode070:爬楼梯官方解决方案

LeetCode078:子集

Given an integer array nums of unique elements, 
return all possible subsets (the power set).

The solution set must not contain duplicate subsets. 
Return the solution in any order.

在这里插入图片描述

思路一:迭代,集合中每添加一个元素,则子集数目增加一倍,且增加的子集为所有原始子集加上新的元素。
思路二:回溯(递归,DFS)。只要知道了subsets(nums[1:]),那么我们只要将nums[0]添加到每个子集的前面形成新的子集,然后将新的子集添加到result中即可。
思路三:hacker编码

class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        return [[nums[j] for j in range(len(nums)) if i>>j&1] for i in range(2**len(nums))]

通过for i in range(2**len(nums))建立一组mask,通过对mask中的每个编码移位,并且和1进行&操作,如果为true,那么将nums[j]添加到result中。
思路一到三的详细解释和代码见Leetcode 78:子集(最详细的解法!!!)
思路四:python中自带的库itertools.combinations(nums, i)。解法参见【python-leetcode78-子集】子集

LeetCode078:子集官方解决方案

任务链接:

team-learning-program/LeetCodeTencent/062 不同路径.md
team-learning-program/LeetCodeTencent/070 爬楼梯.md
team-learning-program/LeetCodeTencent/078 子集.md

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值