-
Notifications
You must be signed in to change notification settings - Fork 0
/
PalindromePartitioningII.cpp
33 lines (31 loc) · 1.03 KB
/
PalindromePartitioningII.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/***
* 动态规划DP
* dpc[i] 用来表示[i,n)之间最小cut
* 初始化:最坏情况下 切分为单个单词
* dpc[i] = min{dpc[j+1] + 1}, j E [i, n)
* 从j切一刀,分为两块 [i, j] [j+1, n)
* 判断子串是否回文也用DP,参见Palindrome Partitioning
* dpb[i][j] = (s[i] == s[j]) && ((j-i < 2) || dpb[i+1][j-1]), i E [0, n), j E [i, n)
* 从后往前计算
***/
class Solution {
public:
int minCut(string s) {
const int n = s.size();
//vector<int> dpc(n + 1);
vector<int> dpc(n);
vector<vector<bool> > dpb(n, vector<bool>(n, false));
//dpc[n] = -1; // can not be cut
for (int i = n-1; i >= 0; --i)
{
dpc[i] = n - 1 - i; // init, the worst case is cutting by each char
for (int j = i; j < n; ++j)
{
dpb[i][j] = (s[i] == s[j]) && ((j-i < 2) || dpb[i+1][j-1]);
if (dpb[i][j]) // can cut here
dpc[i] = (j == n-1) ? 0 : min(dpc[i], dpc[j+1] + 1); // need not be cut
}
}
return dpc[0];
}
};