LeetCode 0294. Flip Game II Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0294. Flip Game II

Description

You are playing a Flip Game with your friend.

You are given a string currentState that contains only '+' and '-'. You and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move, and therefore the other person will be the winner.

Return true if the starting player can guarantee a win, and false otherwise.

 

Example 1:

Input: currentState = "++++"
Output: true
Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+".

Example 2:

Input: currentState = "+"
Output: false

 

Constraints:

  • 1 <= currentState.length <= 60
  • currentState[i] is either '+' or '-'.
  • There cannot be more than 20 consecutive '+'.

 

Follow up: Derive your algorithm's runtime complexity.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def canWin(self, currentState: str) -> bool: @cache def dfs(mask): for i in range(n - 1): if (mask & (1 << i)) == 0 or (mask & (1 << (i + 1)) == 0): continue if dfs(mask ^ (1 << i) ^ (1 << (i + 1))): continue return True return False mask, n = 0, len(currentState) for i, c in enumerate(currentState): if c == '+': mask |= 1 << i return dfs(mask)(code-box)

Solution 2

PythonJavaC++Go
class Solution: def canWin(self, currentState: str) -> bool: def win(i): if sg[i] != -1: return sg[i] vis = [False] * n for j in range(i - 1): vis[win(j) ^ win(i - j - 2)] = True for j in range(n): if not vis[j]: sg[i] = j return j return 0 n = len(currentState) sg = [-1] * (n + 1) sg[0] = sg[1] = 0 ans = i = 0 while i < n: j = i while j < n and currentState[j] == '+': j += 1 ans ^= win(j - i) i = j + 1 return ans > 0(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !