当前位置:网站首页>LeetCode_ Backtracking_ Dynamic programming_ Medium_ 131. split palindrome string

LeetCode_ Backtracking_ Dynamic programming_ Medium_ 131. split palindrome string

2022-06-22 23:16:00 I've been up and down in the Jianghu

1. subject

Give you a string s, Would you please s Split into some substrings , So that each substring is Palindrome string . return s All possible segmentation schemes .

Palindrome string It's the same string read forward and backward .

Example 1:
Input :s = “aab”
Output :[[“a”,“a”,“b”],[“aa”,“b”]]

Example 2:
Input :s = “a”
Output :[[“a”]]

Tips :
1 <= s.length <= 16
s It's only made up of lowercase letters

source : Power button (LeetCode)
link :https://leetcode.cn/problems/palindrome-partitioning

2. Ideas

(1) to flash back _ Dynamic programming
Train of thought reference Official solution to this problem .

3. Code implementation (Java)

// Ideas 1———— to flash back _ Dynamic programming 
class Solution {
    
    
    //dp[i][j]  Express  s[i...j]  Whether it is palindrome string 
    boolean[][] dp;
    //res  Save the final result 
    List<List<String>> res = new ArrayList<>();
    //path  Save qualified results in the backtracking process 
    List<String> path = new ArrayList<>();
    // String length 
    int length;
    
    public List<List<String>> partition(String s) {
    
        length = s.length();
        dp = new boolean[length][length];
        for (int i = 0; i < length; i++) {
    
            Arrays.fill(dp[i], true);
        }
        for (int i = length - 1; i >= 0; i--) {
    
            for (int j = i + 1; j < length; j++) {
    
                dp[i][j] = (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]);
            }
        }
        backtrace(s, 0);
        return res;
    }
    
    public void backtrace(String s, int i) {
    
        if (i == length) {
    
            res.add(new ArrayList<String>(path));
            return;
        }
        for (int j = i; j < length; j++) {
    
            if (dp[i][j]) {
    
                path.add(s.substring(i, j + 1));
                backtrace(s, j + 1);
                path.remove(path.size() - 1);
            }
        }
    }
}
原网站

版权声明
本文为[I've been up and down in the Jianghu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221504017113.html