Java 算法 - Can I Win(記憶化搜索)

  今天在LeetCode上刷到一道題,這道題的解決方法是我之前沒有遇到,因此記錄一下。

題意

In the "100 game," two players take turns adding, to a running total, any integer from 1..10. The player who first causes the 
running total to reach or exceed 100 wins.

What if we change the game so that players cannot re-use integers?

For example, two players might take turns drawing from a common pool of numbers of 1..15 without replacement until they reach a 
total >= 100.

Given an integer maxChoosableInteger and another integer desiredTotal, determine if the first player to move can force a win, 
assuming both players play optimally.

You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger than 300.

樣例

Input:
maxChoosableInteger = 10
desiredTotal = 11

Output:
false

Explanation:
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.

1.解題思路

  初次看到這道題,我打算使用動態規劃的方法,但是發現動規的方程寫不出來,於是又打算使用深搜,但是發現也不是那麼簡單,最終參考了大佬的代碼,不得不說,記憶化搜索之前還真沒有接觸。

2. 代碼

   public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
        int sum = 0;
        for (int i = 1; i <= maxChoosableInteger; i++) {
            sum += i;
        }
        if (sum < desiredTotal) {
            return false;
        }
        Map<Integer, Boolean> map = new HashMap<>();
        return canWin(maxChoosableInteger, desiredTotal, 0, map);
    }

    public boolean canWin(int maxChoosableInteger, int desiredTotal, int used, Map<Integer, Boolean> map) {
        if (map.containsKey(used)) {
            return map.get(used);
        }
        for (int i = 1; i <= maxChoosableInteger; i++) {
            // 判斷該數字是否已經被選
            if ((used & (1 << i)) == 0) {
                // used | (1 << i) 狀態轉移,表示記錄該數字已經被選
                if (desiredTotal <= i || !canWin(maxChoosableInteger, desiredTotal - i, used | (1 << i), map)) {
                    map.put(used, true);
                    return true;
                }
            }
        }
        map.put(used, false);
        return false;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章