Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

climbing stairs

// Key intuition - the # of unique ways of reaching n depends on
// how many ways you can reach step n - 1 PLUS step n - 2
// n = n - 1 + n - 2

export function solution(n: number) {
  let one = 1 // # of ways you can get to n - 1
  let two = 1 // # of ways you can get to n - 2

  // traverse and calculate the new values for n - 1 and n - 2
  for (let i = 0; i < n - 1; i++) {
    let temp = one // one is currently n - 1

    // this moves n - 1 up to n (n = n - 1 + n - 2)
    one = one + two

    // this moves n - 2 up to n - 1 
    two = temp
  }

  return one
}
Source by leetcode.com #
 
PREVIOUS NEXT
Tagged: #climbing #stairs
ADD COMMENT
Topic
Name
1+2 =