Leetcode: Climbing Stairs

来源:互联网 发布:淘宝买家评价语大全 编辑:程序博客网 时间:2024/05/06 00:40

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?

The following solution uses the equation step[ i ] = step[i - 1] + step[i - 2], but require O(n) space.

public class Solution {    public int climbStairs(int n) {        int[] step = new int[n + 1];        step[0] = 1;        step[1] = 1;        for (int i = 2; i <= n; i++) {            step[i] = step[i - 1] + step[i - 2];        }        return step[n];    }}

Since we don't need the results of previous steps, there's no need to use an array. Only need to store the last result. So revise the above code to the following:

public class Solution {    public int climbStairs(int n) {        int last = 1;        int lastlast = 1;        int res = 1;        for (int i = 2; i <= n; i++) {            res = last + lastlast;            lastlast = last;            last = res;        }        return res;    }}


0 0
原创粉丝点击