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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章