Sword Finger Offer 10- II. The Problem of Frog Jumping (C++) Dynamic Programming

A frog can jump up to one or two steps at a time. Find the total number of jumping methods the frog jumps on an n-level step.

The answer needs to be modulo 1e9+7 (1000000007). If the initial result of the calculation is: 1000000008, please return 1.

Example 1:

输入:n = 2
输出:2

Example 2:

输入:n = 7
输出:21

Example 3:

输入:n = 0
输出:1

prompt:

0 <= n <= 100
Note: This question is the same as the 70 question on the main site: https://leetcode-cn.com/problems/climbing-stairs/

Dynamic programming

f(x) = f(x - 1) + f(x - 2)

Idea reference: https://blog.csdn.net/qq_30457077/article/details/114276198

class Solution {
    
    
public:
    int numWays(int n) {
    
    
        int p = 0, q = 0, r = 1;//初始化p为0 q为f(0)==0 r为f(1)==1
        //p q r分别指f(x - 2) f(x - 1) f(x) 
        for (int i = 1; i <= n; ++i) {
    
    
            p = q; 
            q = r; 
            r = (p + q) % 1000000007;
        }
        return r;
    }
};

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114644214