【Depth-first search DFS】Lintcode 136. Split palindrome

Lintcode 136. Split palindrome

Title description: Given a string, split it, and each part after splitting is a palindrome string (these split parts can form the original string). Finally, we return to all possible such palindrome splitting schemes.
Insert picture description here

One conclusion can be remembered: all cutting problems are combined problems.

Why do you say that? For example, to cut "abc", you can put a number in the middle of them to become: a1b2c, so the corresponding relationship between cutting and combination is as follows:
Cutting plan: a | b | c Corresponding combination plan: [1, 2]
Cutting plan: a | bc Corresponding combination plan: [1]
Cutting plan: ab | c Corresponding combination plan: [2]
Cutting plan: abc Corresponding combination plan: []

So: the problem of cutting n letters ==> the problem of combining n-1 numbers

The code implementation uses DFS to imitate the problem of combination to solve:

class Solution {
    
    
public:
    /*
     * @param s: A string
     * @return: A list of lists of string
     */
    vector<vector<string>> partition(string &s) {
    
    
        vector<vector<string>> result;
        if (0 == s.length()) {
    
    
            return result;
        }
        
        vector<string> partition;
        //4、递归的调用
        helper(s, 0, partition, result);
        return result;
    }
    
    //1、递归的定义
    void helper(string &s, int startIdx, vector<string> &partition, vector<vector<string>> &result) {
    
    
        //3、递归的出口
        if (s.size() == startIdx) {
    
    
            
            result.push_back(partition);
            return;
        }
        
        //2、递归的拆解
        //"aaab"
        for (int i = startIdx; i < s.size(); ++i) {
    
    
            string substring = s.substr(startIdx, i - startIdx + 1);
            if (!isPalindrome(substring)) {
    
    
                continue;
            }
            
            partition.push_back(substring);
            helper(s, i + 1, partition, result); 
            partition.pop_back();
        }
        
    }
    
    //回文串判断
    bool isPalindrome(string &s) {
    
    
        for (int i = 0, j = s.size() - 1; i < j; ++i, --j) {
    
    
            if (s.at(i) != s.at(j)) {
    
    
                return false;
            }
        }
        return true;
    }
};

Guess you like

Origin blog.csdn.net/phdongou/article/details/113770043