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.
題目大意:猜給定範圍的數字,猜錯了需要付相應的錢,求贏得遊戲所需的最少的錢。
代碼
package DP; /** * @author OovEver * 2018/1/8 13:46 */ public class LeetCode3752 { public static int getMoneyAmount(int n) { // 其中dp[i][j]表示從數字i到j之間猜中任意一個數字最少需要花費的錢數 int[][] dp = new int[n + 1][n + 1]; // j代表當前的處理長度 for(int j=2;j<=n;j++) { for(int i=j-1;i>0;i--) { int globalMin = Integer.MIN_VALUE; for(int k=i+1;k<j;k++) { int localMax =k+ Math.max(dp[i][k - 1], dp[k + 1][j]); globalMin = Math.min(globalMin, localMax); } dp[i][j] = i + 1 == j ? i : globalMin; } } return dp[1][n]; } }