Leetcode: palindrome partitioning [1, 131]

Source: Internet
Author: User
[Question]

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

Return all possible palindrome partitioning of S.

For example, given S ="aab",
Return

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

Question]

Given a string S, Division of S is required. After division, each substring is a return string.
All division conditions must be returned.


[Idea]

The intuitive idea is to use layer-by-layer recursion. First, determine the first vertex, then the second vertex, then the third vertex, and so on. This method has a very high time complexity.

This question uses DP: calculate whether the substring between the two positions I and J is a return string, which is represented by ispalindrome [I] [J.


[Code]
Class solution {public: void getpartition (vector <string> & result, vector <string> & splits, int start, string & S, vector <vector <bool> & ispal) {// spits-split result, start-current split start position if (START = S. length () {vector <string> newsplits = splits; result. push_back (newsplits); return;} For (INT end = start; end <S. length (); End ++) {If (ispal [start] [end]) {splits. push_back (S. substr (START, end-start + 1); getpartition (result, splits, end + 1, S, ispal); splits. pop_back () ;}}vector <vector <string> partition (string s) {vector <string> result; int Len = S. length (); If (LEN = 0) return result; vector <bool> ispal (Len, vector <bool> (Len, false )); // initialize ispal [I] [I] = true; For (INT I = 0; I <Len; I ++) ispal [I] [I] = true; // initialize a substring consisting of two adjacent characters for (INT I = 0; I <len-1; I ++) if (s [I] = s [I + 1]) ispal [I] [I + 1] = true; // determine the position of other I <j For (INT I = len-3; I> = 0; I --) for (Int J = I + 2; j <Len; j ++) ispal [I] [J] = (s [I] = s [J]) & ispal [I + 1] [J-1]; // determine all combinations of vector <string> splits; getpartition (result, splits, 0, S, ispal ); return result ;}};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.