Algorithm exercises--dynamic programming related

Article directory

A grid plan

Please calculate n*m ​​chessboard grids (n is the number of horizontal grids, m is the number of vertical grids) starting from the upper left corner of the chessboard and walking along the edge line from the upper left corner to the lower right corner. How many moves are there in total? The requirement cannot be Go back, that is: you can only go right and down, but not left or up.

Note: Walk along the edge lines between the checkerboards

Input description:
Enter two positive integers n and m, separated by spaces. (1≤n,m≤8)

Output description:
Output one line of results

Example 1
input:
2 2
output:
6

python implementation:

  • recursion
  • The number of first steps to the right + the number of first steps downwards
  • Similar to climbing stairs
def func(n, m):
    if n < 0 or m < 0:
        return 0 # 没法走
    elif n == 0 or m == 0:
        return 1

    return func(n-1, m) + func(n, m-1)

def walk():
    n, m = input().strip().split()
    n = int(n)
    m = int(m)

    return func(n, m)


print(walk())
  • factorial
import math
def walk():
    row, col = map(int, input().split())
    total_step = col + row
    res = math.factorial(total_step) / (math.factorial(col) * math.factorial(row))
    print(int(res))

walk()

  • dynamic programming
  • Construct a two-dimensional array
  • The number of methods of each point = the sum of the number of methods of the upper point + the left point
def walk():
    n,m = map(int, input().split(' '))
    dp = [[1 for i in range(n+1)] for j in range(m+1)]
    for i in range(1,m+1):
        for j in range(1,n+1):
            dp[i][j] = dp[i-1][j]+dp[i][j-1]
    print(dp[m][n])

walk()

 

choir

Insert image description here
Input description:
The use case has two lines of data. The first line is the total number of students N, and the second line is the height of N students, separated by spaces.

Output description:
At least a few students need to be listed

Example 1
input:
8
186 186 150 200 160 130 197 200
output:
4

Note:
Since the order of the queue elements is not allowed to be changed, the final remaining queue should be 186 200 160 130 or 150 200 160 130

import sys


# 获取最大增长子序列
def get_max_up_sub_arr(count, arr):
    up_arr = [1 for x in range(count)]
    for i in range(count):
        for j in range(i):
            if arr[j] < arr[i]:
                up_arr[i] = max(up_arr[i], up_arr[j] + 1)
    return up_arr


while True:
    try:
        count = int(input())
        arr = list(map(int, input().split(" ")))
        left_up_arr = get_max_up_sub_arr(count, arr)
        right_up_arr = get_max_up_sub_arr(count, arr[::-1])[::-1]
        print(count - max(i + j - 1 for i, j in zip(left_up_arr, right_up_arr)))
    except EOFError:
        break

Guess you like

Origin blog.csdn.net/weixin_45228198/article/details/132222358