【18】Dynamic programming DP

think:

Dynamic programming is to convert the optimal solution to a large problem into the optimal solution to multiple small problems (so the optimal solution for each problem must be considered). The following are the specific problem-solving steps of dynamic programming: (1) Define each
problem a small question

(For example, dp[i] is the maximum number of ways that can be taken when there are n steps)
(2) Find the recurrence relationship (usually dp[i]=dp[i-1]+dp[i-2])

(3) Initialization

(The first dp[0], usually there are two dp[0], dp[1])

(4) Use (2) to calculate the optimal solutions to all problems

(5) dp[n] is the optimal solution to the original big problem

topic

This is very similar to Fibonacci numbers ([i]=[i-1]+[i-2])

Specific problem-solving steps:
(1) Define each small problem: dp[i] is the maximum number of ways to go when there are n steps
(2) Find the recurrence relationship: dp[i]=dp[i-1]+dp[ i-2])

(3) Initialization

dp[0]=1--------------------There is only 1 type when there are 0 steps

dp[1]=1--------------------There is only 1 type for 1 step

(4) Use (2) to calculate the optimal solutions to all problems

For example: dp[2]=dp[1]+dp[0]----------When there are 2 steps, there are 1+1 ways to move (1+1, 0+1)

(5) dp[n] is the optimal solution to the original big problem

for i=0;i<=n;i++{

        dp[n]=dp[n-1]+dp[n-2]

}

dp[n]=dp[n-1]+dp[n-2]=   dp[n-2]+dp[n-3]    +   dp[n-3]+dp[n-4]

= dp[n-3]+dp[n-4]     +2( dp[n-4]+dp[n-5]  )  +  dp[n-5]+dp[n-6]

=dp[n-3]+3dp[n-4] + 3 dp[n-5]  )  +dp[n-6]

//?.?

code

func climbStairs(n int) int {
	if n <= 1 {
		return 1 // 如果楼梯只有0阶或1阶,只有一种方法
	}

	dp := make([]int, n+1) // 创建一个数组来存储每个阶梯的方法数
	dp[0] = 1              // 初始状态:0阶楼梯只有1种方法(不爬)
	dp[1] = 1              // 初始状态:1阶楼梯只有1种方法(爬1步)

	for i := 2; i <= n; i++ {
		// 每次可以选择爬1阶或2阶,所以方法数等于前两阶之和
		dp[i] = dp[i-1] + dp[i-2]
	}

	return dp[n] // 返回n阶楼顶的方法数
}

Guess you like

Origin blog.csdn.net/weixin_67225910/article/details/132599472