0

Given a line from 0 to n points and starting point x and end point y and string which consists only "F" and "B"(F-forward and B-backward). I need to find all subsequence which can lead from starting point to end point.

For example: n=6, x=1, y=2 and String=FFBFBF answer is 7. because there are subsequences F, FFB, FBF,BFF,FFBFB,FBFBF,FFBBF which can lead us from 1 to 2.

I was thinking of find all subsequence and then find it's value assuming F=1 and B=-1, so I can get the how many unit I can move using subsequence. But can anyone suggests me if there is any better way to solve it better way in terms of Time complexity.

abhi2244
  • 13
  • 5

1 Answers1

0

first we suppose y > x, then we need at least (y-x) F's. Now we can add pairs FB (that is +1 -1 = 0, it means that we go to y+1 and then return to y).

We start with (x-y) Fs, with that we just have 1 solution (FF...FF).

We add a pair FB, that means we have now (x-y+1)F's and 1 B, so we can compute the ways to place the Fs with (x-y+2)C(x-y+1) = (x-y+2)!/((x-y+1)! (1)!). The ways to choose (x-y+1) positions of (x-y+2).

Then, we add a new pair FB. Now we have (x-y+2)F's and 2 B's. We compute

(x-y+4)C(x-y+2) = (x-y+4)! / ((x-y+2)!(2)!)

And continue (x-y+2*k)C(x-y+k) = (x-y+2k)! / ((x-y+k)!(k)!)

Continue with that process until x-y+2*k <= n. The sum of all it are the solution

In the case y < x is the same just change the F by B.

EmmanuelAC
  • 141
  • 3