Frog jumping steps (C#)

Recursive memory search dynamic programming time complexity O(n) space complexity O(1)

describe

A frog can jump up 1 step or 2 steps at a time. Find out how many ways the frog can jump up an n-level step (different results will be calculated in different orders).

Data range: 1≤n≤40 1≤n≤40

Requirements: Time complexity: O(n)O(n)O(n), Space complexity: O(1)O(1)O(1)

Example 1

enter:

2

return value:

2

illustrate:

There are two ways for a frog to jump up two steps: jump one level first, then jump one level, or jump two levels directly. So the answer is 2       
class Solution {
    public int jumpFloor(int number) {
        // write code here
        //斐波拉契数列
        //动态规划,规划掉递归栈空间
        int a = 1;//a代表f(n-2)
        int b = 2;//b代表f(n-1)
        int c = 0;//c代表f(n)总方法数
        //fn=f(n-1)+f(n2)
        if (number == 1 || number == 2) return number;
        for (int i = 3; i <= number; i++) {
            //动态规划
            c = a + b;
            a = b;
            b = c;
        }
        return c;

Guess you like

Origin blog.csdn.net/qq_43801336/article/details/130044381