[Leetcode] 131. Palindrome-partitioning (backtracking) [medium]

link

https://leetcode-cn.com/problems/palindrome-partitioning/

time consuming

Problem solving: 24 min
Problem solving: 35 min

Title

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

Return all possible splitting schemes for s.

Ideas

With position 0 as the first character of the substring, every time a palindrome is found, the palindrome is added to the divided array, and then the next position of the substring to the end of the original string is used as a new string (repeat sub-problem) Carrying out the above process, when the next position of the substring is the end of the original string, the divided array is added to the result. When backtracking, delete the current palindrome string from the divided array.

Time complexity: O (n 2 2 n) O(n^22^n)O ( n22n)

AC code

class Solution {
    
    
public:
    string s;
    vector<string> res;
    vector<vector<string>> ans;
    int len;
                
    bool IsPalindromeString(string s) {
    
    
        int n = s.size();
        for(int i = 0; i < n/2; ++i) {
    
    
            if(s[i] != s[n-1-i]) 
                return false;
        }
        return true;
    }               
                                        
    void dfs(int start_pos) {
    
    
        if(start_pos == len) {
    
    
            ans.push_back(res);
            return ;
        }
        for(int i = start_pos; i < len; ++i) {
    
    
            string tes_str = s.substr(start_pos, i-start_pos+1);
            if(IsPalindromeString(tes_str)) {
    
    
                res.push_back(tes_str);
                dfs(i+1);
                res.pop_back();
            }
        }
    }
                                        
    vector<vector<string>> partition(string s) {
    
    
        this->s = s;
        len = s.size();
        dfs(0);
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/Krone_/article/details/114477833