leetcode Palindrome Partitioning II

本文探讨了如何解决字符串切割成多个回文子串的问题,并通过动态规划的方法进行了算法优化,有效避免了超时问题。

起初分析题目 | 与 ||, 发现 || 可以在 | 的基础上稍作改变即可,提交如下代码后发现对于数据量比较大的测试用例出现超时问题。

超时的代码:

class Solution
{
public:
	int minCut(string s)
	{
	   
		int size = s.length();
		 min = size+1;
		vector<bool> flag(size, false);
		bool **partitionLoc = new bool *[size];
		for(int i = 0; i < size; ++i)
		{
			partitionLoc[i] = new bool[size];
			for(int j = 0; j < size; ++j)
				partitionLoc[i][j] = false;
		}		

		for(int i = 1; i <= size; ++i)
		{
			string substr = s.substr(0,i);
			if(judgePalindrome(substr))
			{
				flag[i-1] = true;
				partitionLoc[i-1][0] = true;
			}

			if(flag[i-1])
			{

				for(int j = 1; j <= size - i; ++j)
				{
					if(judgePalindrome(s.substr(i,j)))
					{
						flag[i+j-1] = true;
						partitionLoc[i+j-1][i] = true;
					}
				}

			}		
		
		}

		vector<int> insertBlankLoc;
		vector<vector<string>> result;
		partitionHelper(s, size, size-1, flag, partitionLoc, insertBlankLoc, result);

		return min;



	
	}

	void partitionHelper(string s, int size, int currentPos, vector<bool> flag, bool **partitionLoc, vector<int> insertBlankLoc, vector<vector<string> > &result)
	{
		if(currentPos==-1)
		{

			if(min>insertBlankLoc.size())
			    min = insertBlankLoc.size();
			return ;
		
		}

		for(int i = 0; i < size; ++i)
		{
			if(partitionLoc[currentPos][i])
			{
				insertBlankLoc.push_back(i);
				partitionHelper(s, size, i-1, flag, partitionLoc, insertBlankLoc, result);
				insertBlankLoc.pop_back();
			}
		}
	
	}


	bool judgePalindrome(string s)
	{
		for(int i = 0 ;i < s.length()/2; ++i)
		{
			if(s[i]!=s[s.length()-i-1])
				return false;
		}

		return true;
	
	}

private:
   int min;


};



后参考博客http://blog.youkuaiyun.com/yutianzuijin/article/details/16850031

其将该问题解释的非常清晰易懂

最后代码为

class Solution{
public:    
    int minCut(string s) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        int len = s.size();  
        int* dp = new int[len+1];  
        for(int i=len; i>=0; i--)  
            dp[i] = len-i;  
        bool** matrix = new bool*[len];  
        for(int i=0; i<len; i++)  
        {  
            matrix[i] = new bool[len];  
            memset(matrix[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 || matrix[i+1][j-1]))  
                {  
                    matrix[i][j] = true;  
                   dp[i] = min(dp[i], dp[j+1]+1);  
                }  
            }  
        return dp[0]-1;  
    }      
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值