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;
时间: 2024-10-08 10:41:46