Leetcode dynamic programming の simple set of questions Training (198 303 746 1025) python

Disclaimer: This article is original, All Rights Reserved https://blog.csdn.net/weixin_41864878/article/details/90513493

198. loot

You are a professional thief to steal street plan of the house. Each room are in possession of some cash, the only constraints affecting steal your neighbor's house is equipped with anti-theft system communicate with each other, if two adjacent houses on the same night, thieves broke into the system will automatically alarm .

Given a representative from each non-negative integer array of Housing storage amount calculated in case you do not touch the alarm device, you can steal the maximum amount to.

Example 1:

Input: [1,2,3,1] Output: 4 Explanation: Housing theft No. 1 (amount = 1), then the theft Housing 3 (amount = 3).
The maximum amount to theft = 3 + 1 = 4. Example 2:

Input: [2,7,9,3,1] Output: 12 Explanation: Housing theft No. 1 (amount = 2), 3 theft Housing (amount = 9), followed by theft. 5
No. Housing (amount = 1).
The maximum amount to theft = 2 + 9 + 1 = 12.

Write very simple equation, the basic idea is to maintain the output of the array is always recording the maximum value of the houses i can steal, more when only comparing the current value of the theft and theft value of a house before, take a maximum of it is OK
RES [I] = RES [I-2] the nums + [I]

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums: return 0
        if len(nums) == 1: return nums[0]
        if len(nums) == 2: return max(nums)
        res = [None]*(len(nums))
        res[0] = nums[0]
        res[1] = max(nums[0], nums[1])
        for i in range(2, len(nums)):
            res[i] = max(res[i-2] + nums[i], res[i-1])
        return res[-1]   

303. Regional and retrieval - Array immutable

Given an array of integers nums, the array element from the sum of the index i to j within the range of elements (i ≤ j), comprising i, j points.

Example:

Given nums = [-2, 0, 3, -5, 2, -1], the summation function sumRange ()

sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 说明:

You can assume that the array can not be changed. It calls sumRange method multiple times.

Slicing directly in python, but it takes very long, so I looked at the answers to the top 5%, and really use the dynamic regulation emmm
Here Insert Picture Description

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums = nums

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return sum(self.nums[i:j+1])
        


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
Dynamic Programming
class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        if nums:
            self.sum = [nums[0]]
            for i in range(1, len(nums)):
                self.sum.append(self.sum[i-1] + nums[i])

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.sum[j] - (self.sum[i-1] if i >= 1 else 0)

746. The minimum cost of climbing stairs

Each index of the array as a ladder, the i-th step corresponding to the physical value takes a non-negative cost [i] (the index starts from 0).

Every time you climb a ladder you have to take physical cost value corresponding to, and then you can choose to continue to climb a ladder or climbing two steps.

You need to find the lowest cost at the top floor. In the beginning, you can choose from index 0 or 1 as the initial elements of the ladder.

Example 1:

Input: cost = [10, 15, 20] Output: 15 Explanation: minimum cost from cost [1] Start, then take a step to the top in two steps, spent a total of 15.
Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation:
the lowest cost approach is the cost [0] starts, one by one after that, skips cost [ 3], spent a total of 6. note:

In length will cost [2, 1000]. Each cost [i] is an Integer type will, in the range [0, 999].

Each layer is the focus of res [i] before the roof must not add to their cost [i], and for the roof can not add a layer of cost [-1] value on this one difference

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        if not cost: return 0 #先讨论一下极限情况
        if len(cost) == 1: return cost[0]
        if len(cost) == 2: return min(cost)
        res = cost
        for i in range(2, len(cost)-1):
            res[i] += min(res[i-2], res[i-1])
        return min(res[len(cost)-2], res[len(cost)-3] + res[len(cost)-1])
        # return min(res[len(cost)-2], res[len(cost)-3] + cost[-1])#也是一样的

1025. divisor Game

Alice and Bob play a game, they take turns. Alice upper hand start.

Initially, there is a number N on the board. In each player's turn, the player needs to do the following:

Is selected as an x, satisfying 0 <x <N, and N% x == 0. Replacement digital x N on the board - with N.
If the player can not perform these operations, it will lose the game.

Only Alice returns True only when the victory in the game, otherwise false. Suppose that two players are in the best state to participate in the game.

Example 1:

Input: Output 2: true interpretation: Alice select 1, Bob can not operate. Example 2:

Input: Output 3: false interpretation: Alice select 1, Bob also select one, then Alice can not operate.

prompt:

1 <= N <= 1000

In fact, I do not know about and there's logic, because the judge sent written questions when they feel strange writing may be wrong, but still through the
rough talk about:
In fact, the title means is to ask whether this operation Solutions (if the index is the first step is an odd number, then step 1 solution) derived even steps
maintains a list of d, each smaller than the recorded value of x number of steps removed the N case will go, and then adding value to go x the number of steps to ok

class Solution(object):
    def divisorGame(self, N):
        """
        :type N: int
        :rtype: bool
        """
        if N == 1: return False
        step = 0
        d = [0]
        for x in range(1, N):
            step += d[-1] #取上一步的结果
            while N % x == 0 and N-x > 0:
                N = N - x
                step += 1
            d.append(step)
            if step % 2 == 1: return True %如果得到奇数步解就直接输出
        return False

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_41864878/article/details/90513493
Recommended