LeetCode:Climbing Stairs

来源:互联网 发布:diy制作软件 编辑:程序博客网 时间:2024/05/02 15:02

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?


这题是求斐波那契数列。

我起初没意识到是斐波那契数列,其实用动态规划的思想也可以做。


package leetcode;public class ClimbingStairs {public static void main(String[] args) {System.out.println(new ClimbingStairs().climbStairs(7));} public int climbStairs(int n) {if (n == 0) {return 0;}if (n == 1) {return 1;}if (n == 2) {return 2;}int[] result = new int[3];result[2] = 1;result[1] = 2;for (int i = 0; i < n - 2; i++) {result[0] = result[1] + result[2];result[2] = result[1];result[1] = result[0];}return result[0];}}


原创粉丝点击