61.分割回文串

7 阅读1分钟

题目链接

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

解法 回溯

思路

这题的回溯大致框架和之前差不多,重点是判定回文串,这里可以用一个辅助函数来帮助判断。

其次就是递归的问题,从字符串的起始位置开始,逐步选择可能的分割点。每次尝试一个新的分割,检查当前部分是否是回文。如果是回文,就继续递归剩余部分。如果直到末尾都能分割成回文,就把答案加到结果集。

代码

function partition(s: string): string[][] {
    const result = [];

    const isPalindrome = (str: string): boolean => {
        for (let i = 0, j = str.length - 1; i < j; i++, j--) {
            if (str[i] !== str[j]) return false;
        }
        return true;
    };

    const dfs = (path, index) => {
        if (index === s.length) {
            result.push([...path]);
            return;
        }

        for (let i = index; i < s.length; i++) {
            const tempStr = s.substring(index, i + 1);
            if (isPalindrome(tempStr)) {
                path.push(tempStr);
                dfs(path, i + 1);
                path.pop();
            }
        }
    }

    dfs([], 0);
    return result;
};

时空复杂度

时间复杂度:O()

空间复杂度:O()