[Stair climbing] Introduction to dynamic programming - detailed explanation

topic:

There are n (n is a positive integer) steps in a building. Xiao Ming can take one step or two steps in one step. Q: How many ways does Xiao Ming climb n steps
to reach the top of the building?

analyze:

In this question, we make a simple derivation:
there is 1 method in total for level 1,
2 methods in total for level 2,
3 methods in total for level 3 (equal to level 2 plus level 1),
and 5 methods in total for level 4 (equal to level 3 Plus 2nd order)
There are 8 methods in total of 5th order (equal to 4th order plus 3rd order)
...
After analysis, we can know:
n-order method = (n-2)-order method + (n-1)-order method
(a bit like Fi Bonacci sequence)

If you have not been in touch with dynamic programming, you can read the problem- solving steps of dynamic programming that I wrote before: dynamic programming solution.
Let’s analyze the problem according to the steps of dynamic programming:
1. The definition of dp array and the meaning of subscript
dp[i] : There are dp[i] methods to reach the i-level.
2. Determine the dp formula
dp[i] = dp[i-2] + dp[i-1]
3. How to initialize the dp array
In this question, dp[0] means reaching the 0th order, and there are dp[0] methods
Then if dp[0] = 0 or dp[0] = 1 is initialized; it is obviously not in line with the meaning in real life, but when we run the code, let dp[0] = 0, it will not work, and n is a positive integer, so we do not consider the case of dp[0].
Then we initialize:
dp[0] = 1; dp[1] = 1; dp[2] = 2
Fourth, determine the traversal order
We use the recursive formula: dp[i] = dp[1-2] + dp[i -1], because the final dp[i] is obtained based on the previous data, so we need sequential traversal (and "from front to back" traversal). Fifth, print the dp
array. We
first deduce it, and then print the dp array. Determine whether there is an error.

code:

traverse:

import java.util.Scanner;

public class Main {
    
    
    public static void main (String[] args) {
    
    
    	Scanner sc = new Scanner(System.in);
    	long n = sc.nextLong();
        int[] a = new int[n + 1];
		a[0] = 0;
		if (n > 0) {
    
    
			a[1] = 1;
		}
		if (n > 1) {
    
    
			a[2] = 2;
		}
		if (n >= 3) {
    
    
			for (int i = 3; i < a.length; i++) {
    
    
				a[i] = a[i - 1] + a[i - 2];
			}
		}
		System.out.println("共有: " + a[n] + " 种上台阶的方法");
    }
}

Or use recursion (the order becomes from back to front)

import java.util.Scanner;

public class Main {
    
    
	public static void main(String[] args) {
    
    
		Scanner scanner = new Scanner(System.in);
		long n = scanner.nextLong();
		System.out.println("共有: " + f(n) + " 种上台阶的方法");
	}
		 
		 
		 //递归
	private static long f(long n) {
    
    
		if(n == 1) {
    
    
			return 1;  
		}else if(n == 2) {
    
    
		    return 2;
		}else {
    
    
		    return (f(n-1)+f(n-2));
		}
	}
}

Guess you like

Origin blog.csdn.net/SLT1210/article/details/123806284