LeetCode-Palindrome Partitioning II

LeetCode OJ上的第一题,很简单的DP,之前轻松就过了小数据,大数据的时候超时了,后来在网上看到说还需要优化一下Palindrome的判断过程,于是用一个二维数据保存字符串中任意两个位置i,j是否是回文的状态。

不过遇到两个问题折腾了两个小时:

1.函数调用的时候字符串参数必须用引用,值传递的话会memory out limit;

2.声明在函数外部的vector<vector<int>> palindrome,在插入元素之前要先调用clear清空;不然会出现莫名其妙的WA或者Runtime Error;

代码如下:

 1 class Solution {
 2 public:
 3     vector<vector<int>> palindrome;
 4     bool isPalindrome(string &s, int start, int end) {
 5         if (palindrome[start][end] != -1) {
 6             return palindrome[start][end];
 7         }
 8         if (s[start] !=  s[end]) {
 9             palindrome[start][end] = 0;
10             return false;
11         }
12         if (start == end - 1) {
13             palindrome[start][end] = 1;
14             return true;
15         }  
16         return (palindrome[start][end] = isPalindrome(s, start + 1, end - 1));
17     }
18     int minCut(string s) {
19         // Start typing your C/C++ solution below
20         // DO NOT write int main() function
21         int len = s.length();
22         if (len <= 1) {
23             return 0;
24         }
25         vector<int> cut(len, 0);
26         vector<int> temp(len, -1);
27         palindrome.clear();
28         for (int i = 0; i < len; i++) {
29             palindrome.push_back(temp);
30             palindrome[i][i] = 1;
31         }
32         for (int i = 1; i < len; i++) {
33             cut[i] = cut[i -1] + 1;
34             for (int j = 0; j < i; j++) {
35                 if (isPalindrome(s, j, i)) {
36                     if (j == 0) {
37                         cut[i] = 0;
38                         break;
39                     }
40                     if (cut[j - 1] + 1 < cut[i]) {
41                         cut[i] = cut[j - 1] + 1;
42                         break;
43                     }
44                 }
45             }
46         }
47         return cut[len - 1];
48     }
49 };

 

posted @ 2013-08-20 01:28  Exio  阅读(250)  评论(0编辑  收藏  举报