[Leetcode] Palindrome Partitioning I

    最近要开始准备找工作了,开始做Leetcode 上面的面试题,暂定每天至少一道。下面是第一道题:

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"]
  ]
通过题目可知,需要返回所有可能的分割,所以只有把所有可能分割都遍历一遍,需要用到DFS。附加要求是返回的所有子串必须是回文串,所以需要对每一个子串都判断是不是回文。通过分析和观察示例可以发现,不同的分割结果中有许多相同的子串。在DFS的递归过程中,可能会多次走过同一个子串。如果每次都要对子串进行回文判定,无疑会导致许多重复劳动。所以此处可以通过DP来对DFS进行加速。
class Solution
{
public:
    vector<vector<string> > res_all; //用来存放所有可能的分割结果
    vector<string> res; //用来存放某一个分割结果
	bool** flag;  //DP 用来记录子串是否是回文,若flag[i][j] == true, 则s_ij为回文串
	bool isPali(string s){
		int len = s.length();
	for(int i = 0;i<=len/2;i++)
		if(s[i] != s[len-i-1]) return 0;
	return 1;	
	}
	vector<vector<string> > partition(string s){
	 int len = s.length();
	  res_all.clear();res.clear();
 flag = new bool*[len];
 for(int i =0;i<len;i++){
	 flag[i] = new bool[len];
	 memset(flag[i],0,len);
 }
 for(int i = 0;i<len;i++){
	 flag[i][i] = true;
	 if(i<len-1 && s[i] == s[i+1]) flag[i][i+1]=true;
 }
 for(int i = 1;i<=len-1;i++){ // i is the step size
	 for(int j=0;j<=len-i-1;j++){  // j is the begin of each loop
		int k = j+i;
		if(s[j] == s[k])
			if(flag[j+1][k-1]){
				flag[j][k] = true;
			}
	 }
 }
//前面是先用DP找出所有可能的回文子串,下面是使用DFS来构造所有可能的回文分割结果 DFS(s, len, -1); return res_all; } void DFS(string s, int len, int lf){ if(lf == (len-1)){ res_all.push_back(res); return; } int next = lf+1; for(int i =next;i<=len-1;i++){ if(flag[next][i] == true){ res.push_back(s.substr(next,i-next+1)); DFS(s,len,i); res.pop_back(); } } } };

  

转载于:https://www.cnblogs.com/CGwolke/p/3258380.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值