[Leetcode] DP--375. Guess Number Higher or Lower II

We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.

However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

Example:

n = 10, I pick 8.

First round:  You guess 5, I tell you that it's higher. You pay $5.
Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round:  You guess 9, I tell you that it's lower. You pay $9.
Game over. 8 is the number I picked. You end up paying $5 + $7 + $9 = $21.

Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.


Solution:


Core steps for Dynamic programming

(1) Define the subproblem
define DP[i][j] the money needs to pay to guarantee a win, so the answer is DP[1][n]
(2) Find the recursion
the number is in [1, n] , guess the number x (from 1 to n). if we pick up k, if k != x
then the worst case complexity to guarantee win is the get the maximum cost: k + max(dp[1,][k-1]), dp[k+1][n])
for all x from 1 to n, the the money needs to pay is dp[i][j] = min(dp[i][j], k + max(dp[1,][k-1]), dp[k+1][n]))
(3) Get the base case
the base case is dp[i][i] = 0 for i == j from 1 to n

 1.  Iterative method

 1 dp = [[0] * (n+1) for i in range(0, n+1)]
 2         print ("dp: ", dp)
 3         
 4         for i in range(n-1, 0, -1):                 #from n-1 to 1
 5             for j in range(i+1, n+1):               #from i+1 to n
 6                 
 7                 dp[i][j] = 2**64
 8                 for k in range(i, j):             #from i to j-1
 9                     dp[i][j] = min(dp[i][j], k + max(dp[i][k-1], dp[k+1][j]))
10                     #print ("dp ij ", i, j, k, dp[i][j])
11         return dp[1][n]
12         

  2. Recursive method

 1    def guesshelper(dp, i, j):
 2             if i >= j: return 0
 3             if dp[i][j] > 0: return dp[i][j]
 4             
 5             dp[i][j] = 2**64
 6             
 7             for k in range(i, j+1):            
 8                 dp[i][j] = min(dp[i][j], k + max(guesshelper(dp, i, k-1), guesshelper(dp, k+1, j)))
 9             
10             return dp[i][j]
11         
12         dp = [[0] * (n + 1) for i in range(n + 1)]
13         return guesshelper(dp, 1, n)
14  
原文地址:https://www.cnblogs.com/anxin6699/p/7073100.html