LeetCode132 Palindrome Partitioning II 分解回文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.

题源:here;完整实现:here
思路:
我们可以直接使用上一题做改进得到答案,但是显然复杂度很高,提交超时。
bool isPalindrome(string s){
	int left = 0, right = s.size() - 1;
	while (left <= right){
		if (s[left] != s[right]) return false;
		left++; right--;
	}

	return true;
}

void helper(string s, int count, int &res){
	if (s.empty()){
		res = min(res, count);
		return;
	}

	string prefix;
	while (!s.empty()){
		prefix += s.substr(0, 1);
		s.erase(0, 1);
		if (isPalindrome(prefix)){
			helper(s, count+1, res);
		}
	}
}

int minCut(string s) {
	int res = INT_MAX;
	helper(s, 0, res);
	return res-1;
}
 我们使用动态规划的方法完成该题:
int minCut2(string s) {
	vector<int> dp(s.size(), 0);
	vector<vector<bool>> mp(s.size(),vector<bool>(s.size(), false));

	for (int i = s.size()-1; i >= 0; i--){
		for (int j = i; j < s.size(); j++){
			if (s[i] == s[j] && (j - i < 2 || mp[i + 1][j - 1]))
				mp[i][j] = true;
		}
	}

	for (int i = 1; i < s.size(); i++){
		if (mp[0][i]){
			dp[i] = 0;
			continue;
		}
		int res = s.size();
		for (int j = 0; j < i; j++){
			if (mp[j+1][i] && res > dp[j] + 1)
				res = dp[j] + 1;
		}
		dp[i] = res;
	}

	return dp[s.size() - 1];
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值