[Leetcode] #131#132 Palindrome Partitioning I & II

Discription:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

[
  ["aa","b"],
  ["a","a","b"]
]

Solution:

bool isPalindrome(const string &s, int begin, int end){
	while (begin < end){
		if (s[begin] != s[end])
			return false;
		begin++;
		end--;
	}
	return true;
}

void partition(string s, vector<vector<string>> &result, vector<string> &temp,int begin,int len) {
	if (begin >= len){
		result.push_back(temp);
		return;
	}		
	for (int i = begin; i < len; i++){
		if (!isPalindrome(s, begin, i))
			continue;
		temp.push_back(s.substr(begin, i - begin + 1));
		partition(s, result, temp, i + 1, len);
		temp.pop_back();
	}
}

vector<vector<string>> partition(string s) {
	vector<vector<string>> result;
	vector<string> temp;
	partition(s, result, temp, 0, s.size());
	return result;
}

Discription:

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.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

Solution:

//超时  
bool isPalindrome(const string &s, int begin, int end){
	while (begin < end){
		if (s[begin] != s[end])
			return false;
		begin++;
		end--;
	}
	return true;
}

void minCut(string s, int &minc,int begin,int len,int temp) { //aaabaa
	if (begin >= len){
		if (temp < minc)
			minc = temp;
		return;
	}		
	for (int i = begin; i < len; i++){	
		if (!isPalindrome(s, begin, i))
			continue;
		if (i != len-1)
			temp += 1;
		minCut(s, minc, i + 1, len, temp);
		if (i != len - 1)
			temp -= 1;
	}
}

int minCut(string s) {
	int minc = s.size() - 1;
	minCut(s, minc, 0, s.size(), 0);
	return minc;
}
//方法二 动态规划
int minCut(string s) {
	int size = s.size();
	if (size == 0){
		return 0;
	}
	vector<vector<bool>> isPal(size, vector<bool>(size));
	vector<int> cut(size);
	for (int i = 0; i < size; ++i){
		cut[i] = i;
		for (int j = 0; j <= i; ++j){
			if (s[j] == s[i] && (i - j <= 1 || isPal[j + 1][i - 1])){
				isPal[j][i] = true;
				if (j == 0){
					cut[i] = 0;
				}
				else{
					cut[i] = min(cut[i], cut[j - 1] + 1);
				}
			}
		}
	}
	return cut[size - 1];
}

GitHub-Leetcode:https://github.com/wenwu313/LeetCode

参考:http://www.2cto.com/kf/201503/379759.html

             https://leetcode.com/problems/palindrome-partitioning-ii/?tab=Solutions

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值