c++ - 从给定的一组数字中找出回文序列的数量

标签 c++ algorithm palindrome

假设我们有一组数字,例如 20 40 20 60 80 60 它可以分解为 2 个回文序列:20 40 2060 80 60。 它也可以分解成 6 个回文序列,每个回文序列包含一个数字。

我们如何在 C++ 中从给定的一组数字中找到尽可能少的回文序列?

PS- 这不是我的作业。真正的问题。

最佳答案

一种直接的方法是从查看每个 O(n3) 子序列并检查它是否是回文开始。一旦我们知道哪些子序列是回文序列,我们就可以在 O(n2) 时间内进行动态规划,以找到覆盖整个序列的连续子序列的最少数量。

对于输入 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;
}

关于c++ - 从给定的一组数字中找出回文序列的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27328491/

相关文章:

java - 检查一个句子是否有相同的词向前和向后

java - 回文中的 substring() 方法

c# - 从 WinService 监视剪贴板

C++: "error collect2: error: ld returned 1 exit status"

c++ - 直接对象初始化与使用转换函数初始化

algorithm - 将递归算法转换为迭代算法的设计模式

java - 通讯录的高效搜索

algorithm - 排序链表最快的算法是什么?

c++ - 在头文件中声明类型时,“unordered_set”未命名类型

java - 双链表实现回文检查器