LeetCode OJ平台上的Climbing Stairs题目用java迭代解决

来源:互联网 发布:校园网络安全教育 编辑:程序博客网 时间:2024/06/05 08:08

题目如下。

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

谢谢木易先森的点拨,f(n)表示爬n个台阶的方法数,f(n) = f(n-1) + f(n-2);

f(1) = 1;

f(2) =2;

以此迭代即可。

public class Solution {    public int climbStairs(int n) {    int s1 = 1;    int s2 = 2;    int result = 0;    if(n < 1)    return 0;    else if(n < 2)    return 1;    else if(n < 3)    return 2;    else{    for(int i = 0; i < n - 2; i ++){    result = s1 + s2;    s1 = s2;    s2 = result;        }    }    return result;    }}


0 0
原创粉丝点击