LintCode1300: Bash Game (DP和数学题)

1300 · Bash Game
Algorithms
Easy

Description
You are playing the following game with your friend: There is a pile of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones.

For example, if there are 4 stones, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

Example
Example 1:

Input:n = 4
Output:False
Explanation:Take 1, 2 or 3 first, the other party will take the last one
Example 2:

Input:n = 5
Output:True
Explanation:Take 1 first,Than,we can win the game
Tags
Company
Adobe

解法1:用DP或memorization。

class Solution {
public:
    /**
     * @param n: an integer
     * @return: whether you can win the game given the number of stones in the heap
     */
    bool canWinBash(int n) {
        vector<bool> dp(n + 1, false);
        if (n <= 0) return false;
        if (n <= 3) return true;
        dp[1] = true; dp[2] = true; dp[3] = true;
        for (int i = 4; i <= n; i++) {
            if (dp[i - 1] == false || 
                dp[i - 2] == false || 
                dp[i - 3] == false) dp[i] = true;
        }
        return dp[n];        
    }
};

上面的方法是O(n),显然太慢。这题可以用数学方法O(1)解决。
1->T 2->T 3->T 4->F 5->T 6->T 7->T 8->F 9->T 10->T 11->T 12->F
因为1,2,3都返回TRUE,4返回FALSE,那么
5的话可以选1个,那对方就是4,会FALSE,所以5会返回TRUE
6的话可以选2个,那对方就是4,会FALSE, 所以6会返回TRUE
7的话可以选3个,那对方就是4,会FALSE, 所以6会返回TRUE
8的话,不管选1个,2个还是3个,对方会是5,6,7,会是TRUE,那8会返回FALSE
所以我们可以看出只要是4的倍数就会返回FALSE,否则返回TRUE。

解法2:

class Solution {
public:
    /**
     * @param n: an integer
     * @return: whether you can win the game given the number of stones in the heap
     */
    bool canWinBash(int n) {
        //return n % 4 != 0;
        return (n & 0x1) || (n & 0x2);
    }
};

class Solution {
public:
    /**
     * @param n: an integer
     * @return: whether you can win the game given the number of stones in the heap
     */
    bool canWinBash(int n) {
        return n % 4 != 0;
    }
};

你可能感兴趣的:(算法,动态规划,leetcode)