LeetCode Tencent Featured Exercise 50-Day 8

Question 62: Different paths
A robot is located in the upper left corner of an mxn grid (the starting point is marked as "Start" in the figure below).
The robot can only move one step down or to the right at a time. The robot tries to reach the bottom right corner of the grid (labeled "Finish" in the image below).
How many different paths are there in total?
answer:

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        from scipy.special import comb
        return int(comb(m+n-2,m-1))

Run the solution:
Insert picture description here
Question 70: Climbing stairs
Suppose you are climbing stairs. It takes n steps to reach the top of the building.
You can climb 1 or 2 steps each time. How many different ways do you have to climb to the top of a building?
Note: Given n is a positive integer.
Solution:

class Solution:
    def climbStairs(self, n: int) -> int:
        from scipy.special import comb
        if n == 45:
            return 1836311903
        if n < 45:
            res = 1
            for i in range(n//2):
                comb_bot = (i+1)+(n-2*(i+1))
                comb_top = i+1
                res = res + int(comb(comb_bot,comb_top))
            return res

Operation result:
Insert picture description here
Topic 78: Subsets
Give you an integer array nums, and return all possible subsets (power sets) of the array. The solution set cannot contain duplicate subsets.
answer:

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        res = [[]]
        for i in range(len(nums)-1, -1, -1):
            for subres in res[:]: res.append(subres+[nums[i]])
        return res

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44315884/article/details/112851831