【算法刷题】leetcode 分割回文串

本文介绍了一种基于深度优先搜索(DFS)与回溯法的字符串回文分割算法,用于找出字符串所有可能的回文子串分割方式,并采用动态规划求解最小分割次数。文章包含详细的算法实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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+回溯

   bool ispalin(int start, int end, string s)
	{
		while (start<end)
		{
			if (s[start]!=s[end])
			{
				return false;
			}
			++start;
			--end;
		}

		return true;
	}
	//DFS 回溯
	void dfs(string s,vector<string>& nres,vector<vector<string>>& res,int pos,int length)
	{
		//chukou
		if (pos >= length)
			res.push_back(nres);
		//从pos开始循环
		for (int i = pos; i < length; ++i)
		{
			//确定一个范围
			int left = pos;
			int right = i;
			if (ispalin(left,right,s))
			{
				nres.push_back(s.substr(pos, i - pos + 1));
				dfs(s,nres,res,i+1,length);
				nres.pop_back();//回溯还原
			}

		}
	}
    
    vector<vector<string>> partition(string s) {
        vector<string> nres;
		vector<vector<string>> res;
		int len = s.length();
		if (len == 0)
			return res;
		dfs(s, nres, res, 0, len);
		return res;
    }

找出最短的分割方法

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 ofs.

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


肯定是动态规划咯     对于dp[i]表示以第i个字符结尾的最短分割次数,

状态转移方程为:   dp[i] = 0     0-i为回文串

                                      =min(dp[j-1]+1)     从j-i为回文串的情况

    bool ispalin(int start, int end, string s)
	{
		while (start<end)
		{
			if (s[start]!=s[end])
			{
				return false;
			}
			++start;
			--end;
		}

		return true;
	}
    int minCut(string s) {
        int len = s.length();
        if(len==0)
            return 0;
        int* dp = new int[len];
        dp[0]=0;
        for(int i=1;i<len;++i)
        {
            if(ispalin(0,i,s))
                dp[i]=0;
            else
                dp[i]=i;
            
            for(int j=1;j<=i;++j)
            {
                
                if(ispalin(j,i,s))
                {
                    dp[i]=min(dp[i],dp[j-1]+1);
                }
                
            }
            
        }
        int res = dp[len-1];
        delete[] dp;
        return res;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值