294. 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 "+--+".

一刷
方法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 winMap = new HashMap();
        return helper(s, winMap);
    }
    
    boolean helper(String s, Map winMap){
        if(winMap.containsKey(s)) return winMap.get(s);
        
        for(int i = 0; i

三刷
同上

class Solution {
    public boolean canWin(String s) {
        if(s == null || s.length()<2) return false;
        Map winMap = new HashMap<>();
        return helper(winMap, s);
    }
    
    public boolean helper(Map winMap, String s){
        if(winMap.containsKey(s)) return winMap.get(s);
        for(int i=0; i

你可能感兴趣的:(294. Flip Game II)