码迷,mamicode.com
首页 > 其他好文 > 详细

total number of hops

时间:2017-12-07 15:19:56      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:let   com   csharp   other   for   with   ++   div   ops   

If you can hop 1, 2, or 3 steps at a time, calculate the total number of possible combinations for `n` steps.

 I thought of it as follows, let S(n) be the # of combinations
to go n steps
a) to go n+3 is the S(n+2) + the hop with distance 1 
b) to go n+3 is the S(n+1) + the hop with distance 2
c) to go n+3 is the S(n) + the hop with distance 3
d) S(n+3) = S(n) + S(n+1) + S(n+2) 
<=> S(n) = S(n-3) + S(n-2) + S(n-1)

it can be computed recursively if you memoize in O(n), otherwise
big-O of S < big-O of T(n) = 3*T(n-1) = O(3^n) (closer bound 
is possible with the master theorem or a more complex prove)

iterative computation will be something like Fibonacci: 

int combinations(int n)
{
  if(n<=1) return 1;
  if(n==2) return 2;
  if(n==3) return 3;
  int sn_3 = 1;
  int sn_2 = 2;
  int sn_1 = 3;
  int s = 0;
  for(int i=3; i<=n; i++) {
    s = sn_3 + sn_2 + sn_1;
    sn_3 = sn_2;
    sn_2 = sn_1;
    sn_1 = s;      
  }
}
return s;

  

total number of hops

标签:let   com   csharp   other   for   with   ++   div   ops   

原文地址:http://www.cnblogs.com/apanda009/p/7998618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!