leetcode 131 分隔回文串 C++ 回溯

博客围绕字符串回文分割问题展开,给定字符串 s,需将其分割成每个子串都是回文串的方案。通过示例展示输入输出,分析采用回溯思想,用下标控制找不同子串,以 lastindex 表示上一添加回文串结束位置,判断子串为回文则添加并递归。

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

描述

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

输入: “aab”
输出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分析

采用回溯的思想,找不同的子串
关键并不是一个个向上添加的,而是用下标来控制
一个lastindex表示上一个已经添加进去的回文串结束的位置,当前可以从lastindex下标开始,取i在[lastindex, length()-1]之间的片段,判断是回文串的话就添加到cur里,然后修改lastindex向下递归

代码

class Solution {
public:
	vector<vector<string>>ans;
	bool isok(string s) {
		int length = s.length();
		int i = 0, j = length - 1;
		while (i < j && i < length && j>0)
		{
			if (s[i] != s[j])
				return false;
			i++;
			j--;
		}
		return true;
	}
	void backtrack(string s, vector<string>cur, int lastindex) {
		int n = s.length();
		if (lastindex >= n)
		{
			ans.push_back(cur);
			return;
		}
		for (int i = lastindex; i < n; i++) {
			string stemp = s.substr(lastindex, i - lastindex + 1); //就是python 的s[lastinde:i+1]
			if (isok(stemp))
			{
				cur.push_back(stemp);
				backtrack(s, cur, i + 1);
				cur.pop_back();
			}
		}
	}
	vector<vector<string>> partition(string s) {
		vector<string>cur;
		backtrack(s, cur, 0);
		return ans;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值