|
| 1 | +/** |
| 2 | + * In the "100 game," two players take turns adding, to a running total, any |
| 3 | + * integer from 1..10. The player who first causes the running total to reach |
| 4 | + * or exceed 100 wins. |
| 5 | + * |
| 6 | + * What if we change the game so that players cannot re-use integers? |
| 7 | + * |
| 8 | + * For example, two players might take turns drawing from a common pool of |
| 9 | + * numbers of 1..15 without replacement until they reach a total >= 100. |
| 10 | + * |
| 11 | + * Given an integer maxChoosableInteger and another integer desiredTotal, |
| 12 | + * determine if the first player to move can force a win, assuming both players |
| 13 | + * play optimally. |
| 14 | + * |
| 15 | + * You can always assume that maxChoosableInteger will not be larger than 20 |
| 16 | + * and desiredTotal will not be larger than 300. |
| 17 | + * |
| 18 | + * Example |
| 19 | + * Input: |
| 20 | + * maxChoosableInteger = 10 |
| 21 | + * desiredTotal = 11 |
| 22 | + * Output: |
| 23 | + * false |
| 24 | + * |
| 25 | + * Explanation: |
| 26 | + * No matter which integer the first player choose, the first player will lose. |
| 27 | + * The first player can choose an integer from 1 up to 10. |
| 28 | + * If the first player choose 1, the second player can only choose integers from 2 up to 10. |
| 29 | + * The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal. |
| 30 | + * Same with other integers chosen by the first player, the second player will always win. |
| 31 | + */ |
| 32 | + |
| 33 | +public class CanIWin464 { |
| 34 | + public boolean canIWin(int maxChoosableInteger, int desiredTotal) { |
| 35 | + if (desiredTotal == 0) return true; |
| 36 | + if (((1 + maxChoosableInteger) / 2 * maxChoosableInteger) < desiredTotal) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + return helper(new boolean[maxChoosableInteger], desiredTotal, new HashMap<>()); |
| 40 | + } |
| 41 | + |
| 42 | + private boolean helper(boolean[] set, int desiredTotal, Map<String, Boolean> memo) { |
| 43 | + if (desiredTotal <= 0) return false; |
| 44 | + String k = setKey(set); |
| 45 | + if (memo.containsKey(k)) return memo.get(k); |
| 46 | + |
| 47 | + for (int i=set.length-1; i>=0; i--) { |
| 48 | + if (!set[i]) { |
| 49 | + set[i] = true; |
| 50 | + if (!helper(set, desiredTotal-i-1, memo)) { |
| 51 | + set[i] = false; |
| 52 | + memo.put(k, true); |
| 53 | + return true; |
| 54 | + } |
| 55 | + set[i] = false; |
| 56 | + } |
| 57 | + } |
| 58 | + memo.put(k, false); |
| 59 | + return false; |
| 60 | + } |
| 61 | + |
| 62 | + private String setKey(boolean[] set) { |
| 63 | + StringBuilder sb = new StringBuilder(); |
| 64 | + for (boolean b: set) { |
| 65 | + sb.append(b ? 't' : 'f'); |
| 66 | + } |
| 67 | + return sb.toString(); |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments