[Leetcode] DP-- 464. 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.

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.


Solution: 
1. the naive method is to get all the possible ways, which is factorial of maxChoosableInteger, maxChoosableInteger!.
 
2.   use recursive and dp memoization to record the state
state means which number has been visited by both. because there are maximum 20 for maxChoosableInteger,
so we define a variable "visited" to record every bit as visited or not
for different state, there is corresponding to win or not by player A, record as hash " winMap[state] " for memoization
recursively call to judge win by drawing elements from 1 to maxChoosableInteger.
when element could be drawed, at the same time left element > desiredTotal or the recursive call funtion,
 player A could win
 
   Then we consider the corner cases:
     if maxChoosableInteger  >desiredTotal:
          player A win
    if the sum of 1 tomaxChoosableInteger is bigger than
    player A loses
 
 1     winMap = {}
 2         def canIWinHelper(total, visited):
 3             if visited in winMap:
 4                 return winMap[visited]
 5             for i in range(1, maxChoosableInteger+1):
 6                 mask = (1 << i)
 7                 if (mask & visited) == 0 and (i >= total or not canIWinHelper(total - i, mask | visited)):
 8                     winMap[visited] = True
 9                     return True
10             winMap[visited] = False
11             return False
12         
13         if maxChoosableInteger > desiredTotal:
14             return True
15         if (1+maxChoosableInteger)*maxChoosableInteger/2 < desiredTotal:      #sum
16             return False
17         
18         return canIWinHelper(desiredTotal, 0)
19         

 

 
posted @ 2017-07-13 21:15  安新  阅读(243)  评论(0编辑  收藏  举报