How to analyze time complexity here?

Suppose you play the following flip game with your friend: for a line containing only these two characters: +and -, you and your friend take turns turning two consecutive ones "++"in "--". The game ends when a person can no longer make a move, and therefore another person wins.

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 clicking the middle "++"to become "+--+".

Here is my code:

public boolean canWin(String s) {

    if(s==null || s.length()<2) return false;
    char[] arr=s.toCharArray();
    return canWinHelper(arr);
}

public boolean canWinHelper(char[] arr){
    for(int i=0; i<arr.length-1; i++){
        if(arr[i]=='+' && arr[i+1]=='+'){
            arr[i]='-';
            arr[i+1]='-';
            boolean win=!canWinHelper(arr);
            arr[i]='+';
            arr[i+1]='+';
            if(win) return true;
        }
    }
    return false;
}

, , , , false. - ?

, , -, . : String, Value: Boolean.

hashmap:

 public boolean canWin(String s){

    if(s==null || s.length()<2) return false;
    HashMap<String,Boolean> map=new HashMap<String,Boolean>();
    return helper(s,map);
 }

 public boolean helper(String s, HashMap<String,Boolean> map){
     if(map.containsKey(s)) return map.get(s);
     for(int i=0; i<s.length()-1; i++){
         if(s.charAt(i)=='+' && s.charAt(i+1)=='+'){
             String fliped=s.substring(0,i)+"--"+s.substring(i+2);
             if(!helper(fliped,map)){
                 map.put(s,true);
                 return true;
             }
         }
     }
     map.put(s,false);
     return false;
 }

, , ?

+4
1

, n = arr.length - 1

n . +, n-2 ..

, n + n (n-2) + n (n-2) (n-4) +... .

n!! (1 + 1/2 + 1/(2 * 4) + 1/(2 * 4 * 8) +...) 1 + 1/2 + 1/(2 * 4) + 1/(2 * 4 * 8) +... , ≤2, O (n!!)

n , n + nn + nnn + n... (n/2 )... * n = n (n ^ (n/2) -1)/(n-1), O (n ^ (n/2))

, , , .

, . , , , + , - , . , , n/2 , 2 ^ (n/2). , , , , O (2 ^ (n/2) * ln (n/2)) O (2 ^ (n/2)).

. , , , , , .

- , / . .

, , , . , , , , 0,01% , , - , - .

, , . , , O() , , , ..

- , , . , n-2, . , ++++++++... +++ - +++++... , n-3, n-2 , n-4. , n-3 , n/2 (n-3) + n/2 (n-2) = n (n-5/2)

, n!= n!! (n-1)!! (n-1)!!! n!!! ≈∛n! , - O ((n!) ^ (5/2)). , x = 3 O ((n!) ^ (X)).

( , O ((n!) ^ (x)), -. O ( (!) ^ ()), 1≤x≤3)

+2

Source: https://habr.com/ru/post/1619727/


All Articles