Problem2: Elimination Game simple c++ recursive solution


  • 2
    A
    class Solution {
    public:
        int lastRemaining(int n) {
            return go(n, 0);
        }
        int go(int n, bool normal) {
            if (!normal) {
                if (n == 1) return 1;
                if (n == 2) return 2;
            } else {
                if (n == 1) return 1;
                if (n == 2) return 1;
            }
            
            if (normal==1 && n%2==0) return 2*go(n/2, !normal)-1;
            else return 2*go(n/2, !normal);
        }    
    };
    
    

    Similar to Fibonacci sequence:

    f[n] = 2 * g[n/2]
    g[n] = 2 * f[n/2] if n%2!=0
    g[n] = 2 * f[n/2] - 1 if n%2==0

    output f[n]


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.