Star

Leetcode 294. Flip GameII

Question:

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.

Explanation:

本来想找规律,后来想想太天真了。用backtracking解,罗列所有的情况,如果下一局对手会输,就表示可以。现在我的算法是o(N!!) discuss中有一个牛逼的game theory博弈论算法,看不懂。有机会可以研究一下,会将time complexity降低到O(N^2)

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public boolean canWin(String s) {
if (s == null || s.length() <2) return false;
char[] charString = s.toCharArray();
for (int i=0; i<s.length()-1; i++) {
if (charString[i] == '+' && charString[i+1] == '+') {
charString[i] = '-';
charString[i+1] = '-';
if (!canWin(String.valueOf(charString))) {
return true;
}
charString[i] = '+'; charString[i+1] = '+';
}
}
return false;
}
}