LeetCode 131. 分割回文串 两种回溯写法

131. 分割回文串

题目来源

131. 分割回文串

题目分析

这道题目要求我们将字符串 s 分割成一些子串,使得每个子串都是回文串。最终,返回所有可能的分割方案。这意味着我们需要遍历所有可能的分割点,并检查每个子串是否为回文。

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文串 。返回 s 所有可能的分割方案。

题目难度

  • 难度:中等

题目标签

  • 标签:回溯

题目限制

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

解题思路

为了解决这个问题,我们可以使用回溯算法。在回溯过程中,我们需要枚举所有可能的分割点,并判断每个子串是否为回文串。如果是回文,则继续递归分割下一个子串;否则跳过当前分割点。

核心算法步骤

  • 输入角度的回溯

    1. 我们从第一个字符开始枚举所有可能的分割点 i
    2. 对于每个 i,检查从 starti 的子串是否为回文。
    3. 如果是回文串,则继续从下一个字符开始递归处理剩余的字符串。
  • 答案角度的回溯

    1. 在每次递归时,将当前路径上的子串添加到结果集中。
    2. 枚举每个可能的分割点,检查子串是否为回文串,然后继续递归分割。
  • 回文判断

    1. 使用相向双指针判断,设置leftright指针,分别指向字符串s的首尾
    2. 如果leftright指向的字符相同,则leftright更新,left向后,right向前,最后遍历完s返回true
    3. 如果leftright指向的字符不同直接返回false

代码实现

以下是实现字符串回文分割的Java代码:

/**
 * 131. 分割回文串
 * @param s 输入的字符串
 * @return ans 所有可能的分割方案
 */
public List<List<String>> partition(String s) {
    List<List<String>> ans = new ArrayList<>();
    if (s.isEmpty()) {
        return ans;
    }
    partition(s, 0, 0, new ArrayList<>(), ans);
    return ans;
}

// 输入角度的回溯
private void partition(String s, int i, int start, ArrayList<String> path, List<List<String>> ans) {
    if (i == s.length()) {
        ans.add(new ArrayList<>(path));
        return;
    }
    if (i < s.length() - 1) {
        partition(s, i + 1, start, path, ans);
    }
    if (isPalindrome(s.substring(start, i + 1))) {
        path.add(s.substring(start, i + 1));
        partition(s, i + 1, i + 1, path, ans);
        path.remove(path.size() - 1);
    }
}

// 判断s是否为回文串
public boolean isPalindrome(String s) {
    int left = 0;
    int right = s.length() - 1;
    while (left < right) {
        if (s.charAt(left) != s.charAt(right)) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

// 答案角度的回溯,枚举子串的结束点也就是下一个分割点的位置
private void partition2(String s, int i, ArrayList<String> path, List<List<String>> ans) {
    if (i == s.length()) {
        ans.add(new ArrayList<>(path));
        return;
    }
    for (int j = i; j < s.length(); j++) {
        if (isPalindrome(s.substring(i, j + 1))) {
            path.add(s.substring(i, j + 1));
            partition2(s, j + 1, path, ans);
            path.remove(path.size() - 1);
        }
    }
}

代码解读

  • 输入角度的回溯

    • 从索引 i 开始递归,如果当前子串是回文,则将其加入路径,并继续递归处理剩余字符串。
    • 通过检查每个分割点,确保只将回文串加入路径。
  • 答案角度的回溯

    • 每次递归时,将当前路径添加到结果集中。
    • 通过枚举可能的分割点,逐步构建回文子串,并将每个满足条件的子串加入路径。

性能分析

  • 时间复杂度O(N * 2^N),其中 N 是字符串的长度。每个字符可能作为回文串的开始和结束点,最多有 2^N 种分割方案。

  • 空间复杂度O(N),递归调用栈的深度为 N

测试用例

你可以使用以下测试用例来验证代码的正确性:

String s = "aab";
List<List<String>> result = partition(s);
System.out.println(result);
// 输出: [["a","a","b"],["aa","b"]]

总结

这道题目通过回溯算法帮助我们理解了如何通过枚举分割点来构建所有可能的回文子串。无论从输入角度还是答案角度,我们都可以高效地解决问题,并找到所有可能的分割方案。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值