464. Can I Win

https://leetcode.com/problems/can-i-win/description/

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.

Example

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.

Sol:

After solving several "Game Playing" questions in leetcode, I find them to be pretty similar. Most of them can be solved using the top-down DP approach, which "brute-forcely" simulates every possible state of the game.

The key part for the top-down dp strategy is that we need to avoid repeatedly solving sub-problems. Instead, we should use some strategy to "remember" the outcome of sub-problems. Then when we see them again, we instantly know their result. By doing this, we can always reduce time complexity from exponential to polynomial.
(EDIT: Thanks for @billbirdh for pointing out the mistake here. For this problem, by applying the memo, we at most compute for every subproblem once, and there are O(2^n) subproblems, so the complexity is O(2^n) after memorization. (Without memo, time complexity should be like O(n!))

For this question, the key part is: what is the state of the game? Intuitively, to uniquely determine the result of any state, we need to know:

  1. The unchosen numbers
  2. The remaining desiredTotal to reach

A second thought reveals that 1) and 2) are actually related because we can always get the 2) by deducting the sum of chosen numbers from original desiredTotal.

Then the problem becomes how to describe the state using 1).

In my solution, I use a boolean array to denote which numbers have been chosen, and then a question comes to mind, if we want to use a Hashmap to remember the outcome of sub-problems, can we just use Map<boolean[], Boolean> ? Obviously we cannot, because the if we use boolean[] as a key, the reference to boolean[] won‘t reveal the actual content in boolean[].

Since in the problem statement, it says maxChoosableInteger will not be larger than 20, which means the length of our boolean[] arraywill be less than 20. Then we can use an Integer to represent this boolean[] array. How?

Say the boolean[] is {false, false, true, true, false}, then we can transfer it to an Integer with binary representation as 00110. Since Integer is a perfect choice to be the key of HashMap, then we now can "memorize" the sub-problems using Map<Integer, Boolean>.

The rest part of the solution is just simulating the game process using the top-down dp.

class Solution {

    Map<Integer, Boolean> map;
    boolean[] used;

    public boolean canIWin(int maxChoosableInteger, int desiredTotal) {

        // Brute force.  Game playing problems are all about brute force basically...

        int sum = (1+maxChoosableInteger) * maxChoosableInteger/2;
        if (sum < desiredTotal) return false;
        if (desiredTotal <= 0) return true;

        map = new HashMap();
        used = new boolean[maxChoosableInteger+1];
        return helper(desiredTotal);

    }

    public boolean helper(int desiredTotal){
        if(desiredTotal <= 0) return false;
        int key = format(used);
        if (!map.containsKey(key)){
            // try every unchosen number as next step
            for (int i = 1; i < used.length; i++){
                if(!used[i]){
                    used[i] = true;
                    // check if this leads to a win (i.e. the other player lose)

                    if (!helper(desiredTotal - i)){
                        map.put(key, true);
                        used[i] = false;
                        return true;
                    }

                    used[i] = false;
                }

            }

            map.put(key, false);
        }

        return map.get(key);
    } 

    // transfer boolean[] to an Integer

    public int format(boolean[] used){
        int num = 0;
        for(boolean b: used){
            // i would never think of using bit manipulation on this....
            num <<= 1;
            if(b) num |= 1;
        }

        return num;
    }

}
时间: 2024-10-12 21:14:30

464. Can I Win的相关文章

状态压缩 - LeetCode #464 Can I Win

动态规划是一种top-down求解模式,关键在于分解和求解子问题,然后根据子问题的解不断向上递推,得出最终解 因此dp涉及到保存每个计算过的子问题的解,这样当遇到同样的子问题时就不用继续向下求解而直接可以得到结果.状态压缩就是用来保存子问题的解的,主要思想是把所有可能的状态(子问题)用一个数据结构(通常是整数)统一表示,再用map把每个状态和对应结果关联起来,这样每次求解子问题时先find一下,如果map里面已经有该状态的解就不用再求了:同样每次求解完一个状态的解后也要将其放入map中保存 状态

LeetCode 464 - Can I Win - Medium (Python)

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 examp

过中等难度题目.0310

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.

继续过中等难度.0309

  .   8  String to Integer (atoi)    13.9% Medium   . 151 Reverse Words in a String      15.7% Medium     . 288 Unique Word Abbreviation      15.8% Medium     . 29 Divide Two Integers      16.0% Medium     . 166 Fraction to Recurring Decimal      17.

LeetCode Problems List 题目汇总

No. Title Level Rate 1 Two Sum Medium 17.70% 2 Add Two Numbers Medium 21.10% 3 Longest Substring Without Repeating Characters Medium 20.60% 4 Median of Two Sorted Arrays Hard 17.40% 5 Longest Palindromic Substring Medium 20.70% 6 ZigZag Conversion Ea

Leetcode problems classified by company 题目按公司分类(Last updated: October 2, 2017)

Sorted by frequency of problems that appear in real interviews.Last updated: October 2, 2017Google (214)534 Design TinyURL388 Longest Absolute File Path683 K Empty Slots340 Longest Substring with At Most K Distinct Characters681 Next Closest Time482

[总结]图

在图的基本算法中,最初需要接触的就是图的遍历算法,根据访问节点的顺序,可分为广度优先搜索(BFS)和深度优先搜索(DFS).深度优先搜索,顾名思义即为一条道走到黑的搜索策略,行不通退回来换另外一条道再走到黑,依次直到搜索完成.其过程简要来说是对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次.宽度优先搜索算法(又称广度优先搜索)是最简便的图的搜索算法之一,这一算法也是很多重要的图的算法的原型.Dijkstra单源最短路径算法和Prim最小生成树算法都采用了和宽度优先搜索类似的思

关于win下Memcached安装步骤

2天对我来说有点煎熬..数据量达到17w的时候 我本地执行查询速度特别慢! 请教了一些php大牛如何解决速度问题,在加了索引和优化sql后还是速度慢!我决定在win环境下用Memcached和memcache 来处理,先声明一下: memcache是php的拓展,memcached是客户端,复杂的说:Memcache模块提供了于memcached方便的面向过程及面向对象的接口,memcached是为了降低动态web应用 从数据库加载数据而产生的一种常驻进程缓存产品. 因为我本地用的是xampp集

Csharp: speech to text, text to speech in win

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86