|
| 1 | +/** |
| 2 | + * 464. Can I Win |
| 3 | + * https://leetcode.com/problems/can-i-win/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. |
| 7 | + * The player who first causes the running total to reach or exceed 100 wins. |
| 8 | + * |
| 9 | + * What if we change the game so that players cannot re-use integers? |
| 10 | + * |
| 11 | + * For example, two players might take turns drawing from a common pool of numbers from 1 to 15 |
| 12 | + * without replacement until they reach a total >= 100. |
| 13 | + * |
| 14 | + * Given two integers maxChoosableInteger and desiredTotal, return true if the first player to |
| 15 | + * move can force a win, otherwise, return false. Assume both players play optimally. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} maxChoosableInteger |
| 20 | + * @param {number} desiredTotal |
| 21 | + * @return {boolean} |
| 22 | + */ |
| 23 | +var canIWin = function(maxChoosableInteger, desiredTotal) { |
| 24 | + const memo = new Map(); |
| 25 | + const sum = (maxChoosableInteger * (maxChoosableInteger + 1)) / 2; |
| 26 | + |
| 27 | + if (desiredTotal <= 0) return true; |
| 28 | + if (sum < desiredTotal) return false; |
| 29 | + |
| 30 | + return check(0, desiredTotal); |
| 31 | + |
| 32 | + function check(state, remaining) { |
| 33 | + if (remaining <= 0) return false; |
| 34 | + |
| 35 | + const key = state.toString(); |
| 36 | + if (memo.has(key)) return memo.get(key); |
| 37 | + |
| 38 | + for (let i = 1; i <= maxChoosableInteger; i++) { |
| 39 | + const mask = 1 << i; |
| 40 | + if (!(state & mask) && (i >= remaining || !check(state | mask, remaining - i))) { |
| 41 | + memo.set(key, true); |
| 42 | + return true; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + memo.set(key, false); |
| 47 | + return false; |
| 48 | + } |
| 49 | +}; |
0 commit comments