[Java] 131. Split palindrome string---learn the backtracking algorithm! ! !

Given a string s, split s into some substrings so that each substring is a palindrome.

Return all possible splitting schemes for s.

Example:

Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

代码:
int[][] dp;

    public List<List<String>> partition(String s) {
    
    
        List<List<String>> res = new ArrayList<>();
        if (null == s || s.length() == 0) {
    
    
            return res;
        }
        int length = s.length();
        /*
        它是一个二维矩阵,有三种状态值:
        0表示之前还没有计算过
        1表示从下表i到j的子串是回文串
        2表示不是回文串
        我们只用到了数组的右上半部分
        当然这里也可以使用char数组,空间复杂度更低
         */
        dp = new int[length][length];
        //初始化,单个字符的肯定是回文串
        for (int i = 0; i < length; i++) {
    
    
            dp[i][i] = 1;
        }

        ArrayList<String> templist = new ArrayList<>();
        helper(res, templist, s, length, 0);
        return res;
    }

    /**
     * 回溯算法
     *
     * @param res      结果集
     * @param templist 中间list
     * @param s        字符串
     * @param length   字符串长度
     * @param index    从当前位置向后组合判断
     */
    private void helper(List<List<String>> res, ArrayList<String> templist, String s, int length, int index) {
    
    
    	//走到这一步就表示走到了最后,添加到结果集
        if (index == length) {
    
    
            res.add(new ArrayList<>(templist));//一定要重新new一个对象,templist可以得到重用
        }
        //走到某一步有若干的选择继续走下一步
        for (int i = index; i < length; i++) {
    
    
            if (isPalindrome(s, index, i)) {
    
    
                templist.add(s.substring(index, i + 1));
                helper(res, templist, s, length, i + 1);
                templist.remove(templist.size() - 1);//回溯算法中回退一定要记得这一步
            }
        }
    }

    //判断是否是回文串,这里首先需要到保存的状态中查看是否之前已经有了,优化时间复杂度
    private boolean isPalindrome(String s, int from, int to) {
    
    
        if (dp[from][to] == 1) {
    
    
            return true;
        } else if (dp[from][to] == 2) {
    
    
            return false;
        } else {
    
    
            for (int i = from, j = to; i < j; i++, j--) {
    
    
                if (s.charAt(i) != s.charAt(j)) {
    
    
                    dp[from][to] = 2;
                    return false;
                }
            }
            dp[from][to] = 1;
            return true;
        }
    }

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/114481628