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 "+--+".
一刷
方法1: backtracking
因为是in turn的游戏,一方胜出,下一方失败。
Time complexity: O(n!), 31ms
public class Solution {
int len;
char[] ss;
public boolean canWin(String s) {
len = s.length();
ss = s.toCharArray();
return canWin();
}
boolean canWin(){
for(int is = 0; is<=len-2; is++){
if(ss[is] == '+' && ss[is+1] == '+'){
ss[is] = '-';
ss[is+1] = '-';
boolean wins = !canWin();
ss[is] = '+';
ss[is+1] = '+';
if(wins) return true;
}
}
return false;
}
}
方法2: 用DP提高速度。19ms
public class Solution {
public boolean canWin(String s) {
if(s == null || s.length()<2) return false;
Map<String, Boolean> winMap = new HashMap<String, Boolean>();
return helper(s, winMap);
}
boolean helper(String s, Map<String, Boolean> winMap){
if(winMap.containsKey(s)) return winMap.get(s);
for(int i = 0; i<s.length(); i++){
if(s.startsWith("++", i)){
String t = s.substring(0, i) + "--" + s.substring(i+2);
if(!helper(t, winMap)){
winMap.put(s, true);
return true;
}
}
}
winMap.put(s, false);
return false;
}
}
三刷
同上
class Solution {
public boolean canWin(String s) {
if(s == null || s.length()<2) return false;
Map<String, Boolean> winMap = new HashMap<>();
return helper(winMap, s);
}
public boolean helper(Map<String, Boolean> winMap, String s){
if(winMap.containsKey(s)) return winMap.get(s);
for(int i=0; i<s.length()-1; i++){
boolean result = true;
if(s.charAt(i) == '+' && s.charAt(i+1) == '+'){
String cur = s.substring(0, i) + "--" + s.substring(i+2);
if(!helper(winMap, cur)){
winMap.put(s, true);
return true;
}
}
}
winMap.put(s, false);
return false;
}
}