131. Palindrome Partitioning

Posted ruruozhenhao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了131. Palindrome Partitioning相关的知识,希望对你有一定的参考价值。

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

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

Approach #1: backtracking. [C++]

class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> ans;
        if (s.length() == 0) return ans;
        
        vector<string> path;
        dfs(s, 0, ans, path);
        
        return ans;
    }
    
private:
    void dfs(const string s, int idx, vector<vector<string>>& ans, vector<string>& path) {
        if (s.length() == idx) {
            ans.push_back(path);
            return;
        }
        
        for (int i = idx; i < s.length(); ++i) {
            if (isPalindrome(s, idx, i)) {
                path.push_back(s.substr(idx, i-idx+1));
                // this is the point code in this problem.
                dfs(s, i+1, ans, path);
                path.pop_back();
            }
        }
    }
    
    bool isPalindrome(const string s, int start, int end) {
        while (start <= end) {
            if (s[start++] != s[end--])
                return false;
        }
        
        return true;
    }
};

  

 

以上是关于131. Palindrome Partitioning的主要内容,如果未能解决你的问题,请参考以下文章

131. Palindrome Partitioning

131. Palindrome Partitioning

131. Palindrome Partitioning

131. Palindrome Partitioning

131. Palindrome Partitioning

131. Palindrome Partitioning