2019-11-09 10:31:09
Problem Description :
Problem Solving :
n = 100, typically O (n ^ 3) dynamic compliance issues. Generally this O (n ^ 3) problems can be solved consider interval dp.
Dp is a typical section three-layer structure, the outermost peripheral section length enumeration, enumeration starting intermediate layer, the innermost layer enumeration truncation point, so the interval dp is often time complexity O (n ^ 3).
public int minimumMoves(int[] arr) { int n = arr.length; int[][] dp = new int[n + 1][n + 1]; for (int i = 0; i < n; i++) dp[i][i] = 1; for (int len = 2; len <= n; len++) { for (int i = 0; i <= n - len; i++) { int j = i + len - 1; dp[i][j] = 1 + dp[i + 1][j]; if (arr[i] == arr[i + 1]) dp[i][j] = Math.min(dp[i][j], 1 + dp[i + 2][j]); for (int k = i + 2; k <= j; k++) { if (arr[k] == arr[i]) { dp[i][j] = Math.min(dp[i][j], dp[i + 1][k - 1] + dp[k + 1][j]); } } } } return dp[0][n - 1]; }