Flip Game I
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 compute all possible states of the string after one valid move.
For example, given s = "++++"
, after one move, it may become one of the following states:
[ "--++", "+--+", "++--" ]
If there is no valid move, return an empty list []
.
分析:
一层处理即可
代码:
vector<string> flipGame(string str) { vector<string> vs; for(int i = 0; i < str.length() - 1; i++) { if(str[i] == '+' && str[i + 1] == '+') { str[i] = str[i + 1] = '-'; vs.push_back(str); str[i] = str[i + 1] = '+'; } } return vs; }
Flip Game II
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.
分析:
第一想法是找到合适的规律,可以直接从当前状态判断是否必胜,经过尝试,难以直接判断;所以采用一般解法,当两边都是没有失误的高手状态下,有以下规律:
1、终结点是必败点(P点);
2、从任何必胜点(N点)操作,至少有一种方法可以进入必败点(P点)
3、无论如何操作, 从必败点(P点)都只能进入必胜点(N点).
这里用到的就是1,2,3规律,对手无点可操作,则以失败终结;自己必胜,则至少一种方法进入下一轮必败点;若不能必胜,则找不到方法进入下一轮必败点;若自己必败,则无论用什么方法下一轮都是必胜点。
代码:
bool canwin(string str) { for(int i = 0; i < str.length() - 1; i++) { if(str[i] == '+' && str[i + 1] == '+') { str[i] = str[i + 1] = '-'; int win = !canwin(str); str[i] = str[i + 1] = '+'; if(win) return true; } } return false; }