Flip Game II
https://leetcode.com/problems/flip-game-ii/description/
You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + 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.
Write a function to determine if the starting player can guarantee a win.
For example, given s = "++++", return true. The starting player can guarantee a win by flipping the middle "++" to become "+--+".
Follow up:
Derive your algorithm's runtime complexity.
Thoughts
可以用博弈论理论得出O(N^2)的解, 但面试时并不会考察. 用DFS + Memorization就可以了.
用递归模拟两个人的玩游戏的步骤, 并把结果存下来. 如果对手步骤返回false, 说明对手无地可下, 当前玩家的步骤返回true.
Code
Analysis
Errors: 1. 不能!canWin(str)直接返回true. 要把该递归调用修改过的str全部改回来.
如果不加memory, T(N) = (N - 2) T(N - 4) = (N - 2) (N - 4) T(N - 6) = .... 由Double factorial可知时间复杂度为O(N!!), 即2 ^ N (N - 1). 加了memory后未知.
Last updated
Was this helpful?