LeetCode 132. Palindrome Partitioning II

本文介绍了一个算法问题:如何计算将字符串分割成多个回文子串所需的最少切割次数。通过使用动态规划方法,文章详细解释了如何实现这一算法,并提供了一个具体的例子来展示其工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <vector>
#include <iostream>
#include <climits>
using namespace std;

/*
  Given a string s, partition s such that every substring of the partition is a palindrome.
  Return the minimum cuts needed for a palindrome partitioning of s.
  For example, given s = "aab",
  Return 1 since the palindrome partitioning ["aa", "b"] could be produced using 1 cut.
*/
// Time Complexity is O(N^3)
int minCut(string s) {
  // minCut(i, j) = minCut(i, k) + minCut(k + 1, j) + 1;
  // if s[i, j] is palindrome, minCut(i, j) = 0;
  // we thus need to 2D array to make the palindrome. and a 2d array to calculate the minvalue.
  int n = s.size();
  vector< vector<bool> > P(n, vector<bool>(n, false));
  vector< vector<int> > minCut(n, vector<int>(n, INT_MAX));
  for(int i = 0; i < n; ++i) {
    P[i][i] = true;
    minCut[i][i] = 0;
  }
  for(int L = 2; L <= n; ++L) {
    for(int start = 0; start < n - L + 1; ++start) {
      int end = start + L - 1;
      if(L == 2) {
        P[start][end] = (s[start] == s[end]);
      } else {
        P[start][end] = ((s[start] == s[end]) && P[start + 1][end - 1]);
      }
      if(P[start][end] == true) minCut[start][end] = 0;
      else {
        for(int k = start; k < end; ++k) {
          minCut[start][end] = min(minCut[start][end], minCut[start][k] + minCut[k+1][end] + 1);
        }
      }
    }
  }
  return minCut[0][n-1];
}
int main(void) {
  cout << minCut("aabaa") << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值