Description
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can
you climb to the top?
Solution
Keep a running total of number of distinct jumps it took us to get to our previous two stairs.
On each loop, sum the values of the two previous stairs as the latest stair's value, our running total.
Setup base cases
Setup base cases of one and two whose values are 1 and 2.
We figure this out from the problem explanation.
Return two at the end of the function where we'll keep our summed total.
1// Initialize our base cases, one and two. Return two at the end2 3var climbStairs = function (n) {4 if (n == 1) return 15 var one = 16 var two = 27 8 return two9};1// We guard for n being 1 as well2 3function climbStairs(n: number): number {4 if (n == 1) return 15 var one = 16 var two = 27 8 return two9};1//2 3class Solution {4 int climbStairs(int n) {5 if (n == 1) {6 return 1;7 }8 9 int one = 1;10 int two = 2;11 12 return two;13 }14}1// Explicit typing of Java with int2 3class Solution {4 public int climbStairs(int n) {5 if (n == 1) {6 return 1;7 }8 int one = 1;9 int two = 2;10 11 return two;12 }13}1#2 3class Solution:4 def climbStairs(self, n: int) -> int:5 if n == 1:6 return 17 one = 18 two = 29 10 return two1// Type inference with :=2 3func climbStairs(n int) int {4 if n == 1 {5 return n6 }7 8 one := 19 two := 210 11 return two12}Iterate until n + 1
We loop up til n + 1 because when we "land" on n + 1 then two
will have the return value we want, the number of distinct ways
to get to that stair.
1//2 3var climbStairs = function (n) {4 if (n == 1) return 15 var one = 16 var two = 27 8 for (var i = 3; i < n + 1; i++) {9 var tmp = one + two10 one = two11 two = tmp12 }13 return two14};1//2 3function climbStairs(n: number): number {4 if (n == 1) return 15 var one = 16 var two = 27 8 for (var i = 3; i < n + 1; i++) {9 var tmp = one + two10 one = two11 two = tmp12 }13 return two14};1//2 3class Solution {4 int climbStairs(int n) {5 if (n == 1) {6 return 1;7 }8 int one = 1;9 int two = 2;10 11 for(var i = 3; i < n + 1; i++) {12 var tmp = one + two;13 one = two;14 two = tmp;15 }16 return two;17 }18}1//2 3class Solution {4 public int climbStairs(int n) {5 if (n == 1) {6 return 1;7 }8 int one = 1;9 int two = 2;10 11 for (var i = 3; i < n + 1; i++) {12 int tmp = one + two;13 one = two;14 two = tmp;15 }16 return two;17 }18}1#2 3class Solution:4 def climbStairs(self, n: int) -> int:5 if n == 1:6 return 17 one = 18 two = 29 10 for i in range(3, n + 1):11 tmp = two12 two = one + two13 one = tmp14 return two1//2 3func climbStairs(n int) int {4 if n == 1 {5 return n6 }7 8 one := 19 two := 210 11 for i := 3; i < n + 1; i++ {12 tmp := one + two13 one = two14 two = tmp15 }16 return two17}Questions? Concerns?
Please comment a better solution if you have one.