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

Follow up: Derive your algorithm's runtime complexity.

T(N) = T(N-2) + T(N-3) + [T(2) + T(N-4)] + [T(3) + T(N-5)] + ... 
        [T(N-5) + T(3)] + [T(N-4) + T(2)] + T(N-3) + T(N-2)
     = 2 * sum(T[i])  (i = 3..N-2)

the runtime complexity will be expotential.


public class Solution {
    public boolean canWin(String s) {
        if(s == null || s.length() == 0) return false;
        char [] arr = s.toCharArray();
        return canWin_(arr);
    }

    private boolean canWin_(char[] arr){
        for(int i=0; i<arr.length-1;i++){
            if(arr[i] == '+' && arr[i+1] == '+'){
                arr[i] = '-';
                arr[i+1] = '-';

                boolean otherWin = canWin_(arr);
                arr[i] ='+';  
                arr[i+1] = '+';
                if(!otherWin) return true; // this need be the last state, cause you need to recovery the scene for other recursive calls to canWin_; if this line happens before the above 2 line, the scene is recovered during the recursive call stack.
            }
        }

        return false;
    }
}

results matching ""

    No results matching ""