-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path131.分割回文串.cpp
52 lines (50 loc) · 1.1 KB
/
131.分割回文串.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* @lc app=leetcode.cn id=131 lang=cpp
*
* [131] 分割回文串
*/
#include "a_header.h"
// @lc code=start
class Solution
{
public:
bool isPalindrome(string str)
{
int n = str.length();
for (int i = 0; i < n / 2; i++)
{
if (str[i] != str[n - i - 1])
{
return false;
}
}
return true;
}
void backtrack(vector<vector<string>> &ret,
vector<string> &cur,
string &s,
int idx)
{
if (idx == s.length())
{
ret.push_back(cur);
}
for (int i = idx; i < s.length(); ++i)
{
if (isPalindrome(s.substr(idx, i - idx + 1)))
{
cur.push_back(s.substr(idx, i - idx + 1));
backtrack(ret, cur, s, i + 1);
cur.pop_back();
}
}
}
vector<vector<string>> partition(string s)
{
vector<vector<string>> ret;
vector<string> cur;
backtrack(ret, cur, s, 0);
return ret;
}
};
// @lc code=end