LeetCode 131. Palindrome Partitioning(dfs)

题目来源:https://leetcode.com/problems/palindrome-partitioning/

问题描述

131. 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.

Example:

Input: "aab"

Output:

[

  ["aa","b"],

  ["a","a","b"]

]

------------------------------------------------------------

题意

给定字符串s,求s的所有“回文字符串切分”。一个“回文字符串切分”是指字符串的一个切分,使得所有子串都是回文串。

------------------------------------------------------------

思路

dfs,对于dfs每一步切分的子串,暴力检测是否回文

------------------------------------------------------------

代码

class Solution {
private:
    void dfs(int i, const string& s, vector& cur, vector>& ret) {
        int n = s.size();
        if (i == n) {
            ret.push_back(vector(cur));
            return;
        }
        for (int j=1; j<=n-i; j++) {    // j: length of substring
            if (checkPal(s.substr(i, j))) {
                cur.push_back(s.substr(i,j));
                dfs(i+j, s, cur, ret);
                cur.pop_back();
            }
        }
    }
    
    bool checkPal(string str) {
        int i = 0, n = str.size();
        for (i=0; i> partition(string s) {
        vector> ret;
        if (s.size() == 0) {
            return ret;
        }
        vector cur;
        dfs(0, s, cur, ret);
        return ret;
    }
};

 

你可能感兴趣的:(LeetCode)