Leetcode之Palindrome Partitioning II

题目:

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.

Example:

Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.

代码:

方法一——在palindrome Partitioning的基础上,但是超时了:

class Solution {
public:
   void helper(vector <vector<bool>>& b, string& s, int start, vector<string>& v, int& min) {
	if (start >= s.size()) {
		if (v.size()-1 < min) { min = v.size()-1; }
		return;
	}
	for (int i = start; i < s.size(); i++) {
                if(v.size()>min)return;
		if (b[start][i]) {
			v.push_back(s.substr(start, i - start + 1));
			helper(b, s, i + 1, v, min);
			v.pop_back();
		}
	}
}
int minCut(string s) {
	int len = s.length();
	vector<vector<bool>> b(len, vector<bool>(len, false));

	for (int i = 0; i < len; i++) {
		for (int j = 0; j <= i; j++) {
			if (s[i] == s[j] && (i - j <= 2 || b[j + 1][i - 1])) {
				b[j][i] = true;
			}
		}
	}

	int res = INT_MAX;
	vector<string> v;
	helper(b, s, 0, v, res);
	return res;
}
};

方法二——简单点的动态规划:

class Solution {
public:
  
int minCut(string s) {
	if (s.empty()) return 0;
        int n = s.size();
        vector<vector<bool>> p(n, vector<bool>(n));
        vector<int> dp(n);
        for (int i = 0; i < n; ++i) {
            dp[i] = i;
            for (int j = 0; j <= i; ++j) {
                if (s[i] == s[j] && (i - j < 2 || p[j + 1][i - 1])) {
                    p[j][i] = true;
                    dp[i] = (j == 0) ? 0 : min(dp[i], dp[j - 1] + 1);
                }
            }
        }
        return dp[n - 1];
}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值