375. Guess Number Higher or Lower II

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.
  • 題目大意:猜給定範圍的數字,猜錯了需要付相應的錢,求贏得遊戲所需的最少的錢。

  • 思路:http://www.cnblogs.com/grandyang/p/5677550.html

  • 代碼

    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];
      }
    }
    
發佈了207 篇原創文章 · 獲贊 69 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章