码迷,mamicode.com
首页 > 其他好文 > 详细

131. Palindrome Partitioning

时间:2019-02-05 23:43:49      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:backtrac   app   ack   rom   path   int   return   input   vector   

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

标签:backtrac   app   ack   rom   path   int   return   input   vector   

原文地址:https://www.cnblogs.com/ruruozhenhao/p/10353303.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!