【LeetCode】100. Palindrome Partitioning

题目描述(Medium)

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

Return all possible palindrome partitioning of s.

题目链接

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

Example 1:

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

算法分析

dfs+循环+回溯;

提交代码(方法一):

class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<string> path;
        vector<vector<string>> result;
        dfs(s, path, result, 0);
        return result;
    }
    
    void dfs(string& s, vector<string>& path, vector<vector<string>>& result, int start) {
        if (start == s.size()) {
            result.push_back(path);
            return;   
        }
        
        for (int i = start; i < s.size(); ++i) {
            if (isPalindrome(s, start, i)) {
                path.push_back(s.substr(start, i - start + 1));
                dfs(s, path, result, i + 1);
                path.pop_back();
            }
        }
    }
    
    bool isPalindrome(string& s, int start, int end) {
        while (start < end && s[start] == s[end])
            ++start, --end;
        
        return start >= end;
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/83241269