Блог пользователя wish_me

Автор wish_me, история, 7 лет назад, По-английски

You are given a string and 2 operators ( & , | ). Return the total number of ways in which you can evaluate to true using the given string and operator set.

Example : Input : TF Output : 1 Input : TFF Output : 2 ( T | F & F , T | F | F )

  • Проголосовать: нравится
  • -25
  • Проголосовать: не нравится

»
7 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

I have come across a problem like this before. But i dont know how to solve it using dp. Someone explain please

»
7 лет назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

I will discuss it using recursion + memoization which can be easily converted to an iterative DP solution.

Let your state be where you are in the given string i, and what is the cumulative (Prefix) answer till now last.

Each time you can either AND this bit s[i] or OR it with last.

After finishing all the string, if last is true return 1, else return 0.

So the code may be something like: Assuming that s is the given string, mem is the memoization array filled initially by -1.

long long findMax(int i = 1, bool last = (s[0]=='T')){
   if(i==s.length())
       return last;
   long long & ret = mem[i][last];
   if(ret != -1)    return ret;
   return ret = findMax(i+1, last&(s[i]=='T')) + findMax(i+1, last|(s[i]=='T'));
}