This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
/** | |
* @param n | |
* @return | |
*/ | |
public int getMoneyAmount(int n) { | |
if (n < 2) { | |
return 0; | |
} | |
// core logic | |
table = new int[n + 1][n + 1]; | |
return dp(1, n); | |
} | |
private int[][] table; | |
private int dp(int start, int end) { | |
if (start >= end) { | |
return 0; | |
} | |
if (table[start][end] != 0) { | |
return table[start][end]; | |
} | |
int min = Integer.MAX_VALUE; | |
for (int i = start; i <= end; i++) { | |
int res = i + Math.max(dp(start, i - 1), dp(i + 1, end)); | |
min = Math.min(min, res); | |
} | |
table[start][end] = min; | |
return min; | |
} | |
} |
No comments:
Post a Comment