?LeetCode刷題實戰(zhàn)294:翻轉(zhuǎn)游戲II
+ 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.示例
輸入: s = "++++"
輸出: true
解析: 起始玩家可將中間的 "++" 翻轉(zhuǎn)變?yōu)?"+--+" 從而得勝。
延伸:
請推導(dǎo)你算法的時間復(fù)雜度。
解題
class Solution {
public:
bool canWin(string s) {
for (int i = 1; i < s.size(); ++i) {
if (s[i] == '+' && s[i - 1] == '+' && !canWin(s.substr(0, i - 1) + "--" + s.substr(i + 1))) {
return true;
}
}
return false;
}
};
評論
圖片
表情
