假设我们得到一组数字,如20 40 20 60 80 60
它可以分为2个回文序列:20 40 20
和60 80 60
。
它也可以分为6个回文序列,每个序列包含一个数字。
我们如何在c ++中找到一组给定数字中最小数量的回文序列?
PS-这不是我的功课。真正的问题。
答案 0 :(得分:4)
通过查看每个O(n 3 )子序列并检查它是否是回文,开始直接的方法。一旦我们知道哪些子序列是回文,我们就可以在O(n 2 )时间内进行动态编程,以找到覆盖整个序列的最小连续子序列数。
对于输入20 40 20 60 80 60
,下面的C ++实现打印[20 40 20] [60 80 60]
。
#include <cstdio>
#include <vector>
using namespace std;
int main() {
// Read the data from standard input.
vector<int> data;
int x;
while (scanf("%d", &x) != EOF) {
data.push_back(x);
}
int n = data.size();
// Look at every subsequence and determine if it's a palindrome.
vector<vector<bool> > is_palindrome(n);
for (int i = 0; i < n; ++i) {
is_palindrome[i] = vector<bool>(n);
for (int j = i; j < n; ++j) {
bool okay = true;
for (int left = i, right = j; left < right; ++left, --right) {
if (data[left] != data[right]) {
okay = false;
break;
}
}
is_palindrome[i][j] = okay;
}
}
// Dynamic programming to find the minimal number of subsequences.
vector<pair<int,int> > best(n);
for (int i = 0; i < n; ++i) {
// Check for the easy case consisting of one subsequence.
if (is_palindrome[0][i]) {
best[i] = make_pair(1, -1);
continue;
}
// Otherwise, make an initial guess from the last computed value.
best[i] = make_pair(best[i-1].first + 1, i-1);
// Look at earlier values to see if we can improve our guess.
for (int j = i-2; j >= 0; --j) {
if (is_palindrome[j+1][i]) {
if (best[j].first + 1 < best[i].first) {
best[i].first = best[j].first + 1;
best[i].second = j;
}
}
}
}
printf("Minimal partition: %d sequences\n", best[n-1].first);
vector<int> indices;
int pos = n-1;
while (pos >= 0) {
indices.push_back(pos);
pos = best[pos].second;
}
pos = 0;
while (!indices.empty()) {
printf("[%d", data[pos]);
for (int i = pos+1; i <= indices.back(); ++i) {
printf(" %d", data[i]);
}
printf("] ");
pos = indices.back()+1;
indices.pop_back();
}
printf("\n");
return 0;
}