[LeetCode] Palindrome Partitioning II

来源:互联网 发布:人工智能在线观看土豆 编辑:程序博客网 时间:2024/06/05 04:07

Use DFS will result in TLE!

DP: dp[i] denotes the minimum number of palindromic substrings from i->n, isPal[i][j] denotes if string(i,j) is palindromic.

Thus we have: 

isPal[i][j] = (s[i]==s[j] && isPal[i+1][j-1]);

dp[i] = min(dp[j]+1), i<j<n.

class Solution {public:    int minCut(string s) {            int len = s.size();    int* dp = new int[len+1];    for(int i=len; i>=0; i--)    dp[i] = len-i;    bool** isPal = new bool*[len];    for(int i=0; i<len; i++) {    isPal[i] = new bool[len];    memset(isPal[i], false, sizeof(bool)*len);    }    for(int i=len-1; i>=0; i--)    for(int j=i; j<len; j++)    if(s[i] == s[j] && (j-i<2 || isPal[i+1][j-1])) {    isPal[i][j] = true;    dp[i] = min(dp[i], dp[j+1]+1);    }    return dp[0]-1;        }};



0 0