在leetcode中,经常会遇到判断两人游戏,一方是输还是赢的问题。有guess number higher or lower,
can I win,predict the winner等。这类问题都假设双方在最优策略下,甲方是否会赢。
这类问题都可以用动态规划来解决,关键在于采用top-down的备忘录策略,每解决一个小的子问题,都把相应的结果记录在备忘录上,下次遇到相同的问题时,直接查询即可。这样可以把原来O(n!)的复杂度降低到O(2^n)的复杂度。
1) can I win:
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.
思路:用hash表记录每种可能的选择所对应的结果,这里map
class Solution {
map<int,bool> m;//用来记录子问题的备忘录
bool helper(int desiredTotal,