comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
困难 |
2203 |
第 12 场双周赛 Q4 |
|
给你一个整数数组 arr
,每一次操作你都可以选择并删除它的一个 回文 子数组 arr[i], arr[i+1], ..., arr[j]
( i <= j
)。
注意,每当你删除掉一个子数组,右侧元素都会自行向前移动填补空位。
请你计算并返回从数组中删除所有数字所需的最少操作次数。
示例 1:
输入:arr = [1,2] 输出:2
示例 2:
输入:arr = [1,3,4,1,5] 输出:3 解释:先删除 [4],然后删除 [1,3,1],最后再删除 [5]。
提示:
1 <= arr.length <= 100
1 <= arr[i] <= 20
我们定义
对于
对于超过两个数字的情况,如果
答案即为
时间复杂度
class Solution:
def minimumMoves(self, arr: List[int]) -> int:
n = len(arr)
f = [[0] * n for _ in range(n)]
for i in range(n):
f[i][i] = 1
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
if i + 1 == j:
f[i][j] = 1 if arr[i] == arr[j] else 2
else:
t = f[i + 1][j - 1] if arr[i] == arr[j] else inf
for k in range(i, j):
t = min(t, f[i][k] + f[k + 1][j])
f[i][j] = t
return f[0][n - 1]
class Solution {
public int minimumMoves(int[] arr) {
int n = arr.length;
int[][] f = new int[n][n];
for (int i = 0; i < n; ++i) {
f[i][i] = 1;
}
for (int i = n - 2; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (i + 1 == j) {
f[i][j] = arr[i] == arr[j] ? 1 : 2;
} else {
int t = arr[i] == arr[j] ? f[i + 1][j - 1] : 1 << 30;
for (int k = i; k < j; ++k) {
t = Math.min(t, f[i][k] + f[k + 1][j]);
}
f[i][j] = t;
}
}
}
return f[0][n - 1];
}
}
class Solution {
public:
int minimumMoves(vector<int>& arr) {
int n = arr.size();
int f[n][n];
memset(f, 0, sizeof f);
for (int i = 0; i < n; ++i) {
f[i][i] = 1;
}
for (int i = n - 2; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
if (i + 1 == j) {
f[i][j] = arr[i] == arr[j] ? 1 : 2;
} else {
int t = arr[i] == arr[j] ? f[i + 1][j - 1] : 1 << 30;
for (int k = i; k < j; ++k) {
t = min(t, f[i][k] + f[k + 1][j]);
}
f[i][j] = t;
}
}
}
return f[0][n - 1];
}
};
func minimumMoves(arr []int) int {
n := len(arr)
f := make([][]int, n)
for i := range f {
f[i] = make([]int, n)
f[i][i] = 1
}
for i := n - 2; i >= 0; i-- {
for j := i + 1; j < n; j++ {
if i+1 == j {
f[i][j] = 2
if arr[i] == arr[j] {
f[i][j] = 1
}
} else {
t := 1 << 30
if arr[i] == arr[j] {
t = f[i+1][j-1]
}
for k := i; k < j; k++ {
t = min(t, f[i][k]+f[k+1][j])
}
f[i][j] = t
}
}
}
return f[0][n-1]
}
function minimumMoves(arr: number[]): number {
const n = arr.length;
const f: number[][] = Array.from({ length: n }, () => Array(n).fill(0));
for (let i = 0; i < n; ++i) {
f[i][i] = 1;
}
for (let i = n - 2; i >= 0; --i) {
for (let j = i + 1; j < n; ++j) {
if (i + 1 === j) {
f[i][j] = arr[i] === arr[j] ? 1 : 2;
} else {
let t = arr[i] === arr[j] ? f[i + 1][j - 1] : Infinity;
for (let k = i; k < j; ++k) {
t = Math.min(t, f[i][k] + f[k + 1][j]);
}
f[i][j] = t;
}
}
}
return f[0][n - 1];
}