For any given value N we have to find the number of ways to reach the top while using steps of 1,2 or 3 but we can use 3 steps only once. for example if n=7 then possible ways could be
[1,1,1,1,1,1,1]
[1,1,1,1,1,2]
etc but we cannot have [3,3,1] or [1,3,3]
I have managed to solve the general case without the constraint of using 3 only once with dynamic programming as it forms a sort of fibonacci series
def countWays(n) :
res = [0] * (n + 1)
res[0] = 1
res[1] = 1
res[2] = 2
for i in range(3, n + 1) :
res[i] = res[i - 1] + res[i - 2] + res[i - 3]
return res[n]
how do I figure out the rest of it?
Let
res0[n]be the number of ways to reachnsteps without using a 3-step, and letres1[n]be the number of ways to reachnsteps after having used a 3-step.res0[i]andres1[i]are easily calculated from the previous values, in a manner similar to your existing code.This is an example of a pretty common technique that is often called "graph layering". See, for example: Shortest path in a maze with health loss