思路:
dp。
https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/
实现:
1 class Solution 2 { 3 public: 4 int getMoneyAmount(int n) 5 { 6 int dp[n + 1][n + 1]; 7 memset(dp, 0x3f, sizeof dp); 8 for (int i = 0; i <= n; i++) 9 dp[i][i] = 0; 10 for (int i = n - 1; i >= 1; i--) 11 { 12 for (int j = i + 1; j <= n; j++) 13 { 14 for (int k = i; k <= j; k++) 15 { 16 dp[i][j] = min(dp[i][j], k + 17 max(i > k - 1 ? 0 : dp[i][k - 1], 18 k + 1 > j ? 0 : dp[k + 1][j])); 19 } 20 } 21 } 22 return dp[1][n]; 23 } 24 };
时间: 2024-10-12 03:38:47