n steps with 1, 2 or 3 steps taken. How many ways to get to the top?

前端 未结 13 763
时光说笑
时光说笑 2020-12-08 08:12

If we have n steps and we can go up 1 or 2 steps at a time, there is a Fibonacci relation between the number of steps and the ways to climb them. IF and ONLY if we do not co

相关标签:
13条回答
  • 2020-12-08 09:15

    This is my solution in Ruby:

    # recursion requirement: it returns the number of way up
    # a staircase of n steps, given that the number of steps
    # can be 1, 2, 3
    
    def how_many_ways(n)
      # this is a bit Zen like, if 0 steps, then there is 1 way
      # and we don't even need to specify f(1), because f(1) = summing them up
      # and so f(1) = f(0) = 1
      # Similarly, f(2) is summing them up = f(1) + f(0) = 1 + 1 = 2
      # and so we have all base cases covered
      return 1 if n == 0
    
      how_many_ways_total = 0
      (1..3).each do |n_steps|
        if n >= n_steps
          how_many_ways_total += how_many_ways(n - n_steps)
        end
      end
      return how_many_ways_total
    end
    
    0.upto(20) {|n| puts "how_many_ways(#{n}) => #{how_many_ways(n)}"}
    


    and a shorter version:

    def how_many_ways(n)
      # this is a bit Zen like, if 0 steps, then there is 1 way
      # if n is negative, there is no way and therefore returns 0
      return 1 if n == 0
      return 0 if n < 0
      return how_many_ways(n - 1) + how_many_ways(n - 2) + how_many_ways(n - 3)
    end
    
    0.upto(20) {|n| puts "how_many_ways(#{n}) => #{how_many_ways(n)}"}
    


    and once you know it is similar to fibonacci series, you wouldn't use recursion, but use an iterative method:

    # 
    # from 0 to 27: recursive: 4.72 second
    #               iterative: 0.03 second
    #
    
    def how_many_ways(n)
      arr = [0, 0, 1]
      n.times do
        new_sum = arr.inject(:+)    # sum them up
        arr.push(new_sum).shift()
      end
      return arr[-1]
    end
    
    0.upto(27) {|n| puts "how_many_ways(#{n}) => #{how_many_ways(n)}"}
    


    output:

    how_many_ways(0) => 1
    how_many_ways(1) => 1
    how_many_ways(2) => 2
    how_many_ways(3) => 4
    how_many_ways(4) => 7
    how_many_ways(5) => 13
    how_many_ways(6) => 24
    how_many_ways(7) => 44
    how_many_ways(8) => 81
    how_many_ways(9) => 149
    how_many_ways(10) => 274
    how_many_ways(11) => 504
    how_many_ways(12) => 927
    how_many_ways(13) => 1705
      .
      .
    how_many_ways(22) => 410744
    how_many_ways(23) => 755476
    how_many_ways(24) => 1389537
    how_many_ways(25) => 2555757
    how_many_ways(26) => 4700770
    how_many_ways(27) => 8646064
    

    I like the explanation of @MichałKomorowski and the comment of @rici. Thought I think if it depends on knowing K(3) = 4, then it involves counting manually.

    0 讨论(0)
提交回复
热议问题