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
class Solution {
private boolean canWin(char[] str, Map<String, Boolean> cache) {
String ss = new String(str);
if (cache.containsKey(ss)) {
return cache.get(ss);
}
for (int i = 0; i < str.length - 1; i++) {
if (str[i] == '+' && str[i + 1] == '+') {
str[i] = '-';
str[i + 1] = '-';
boolean res = !canWin(str, cache);
str[i] = '+';
str[i + 1] = '+';
if (res) {
cache.put(ss, true);
return true;
}
}
}
cache.put(ss, false);
return false;
}
public boolean canWin(String s) {
return canWin(s.toCharArray(), new HashMap<>());
}
}
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?