131. Palindrome Partitioning
Problem statement:
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"]]
Solution:
This problem returns all possible palindrome partitions. Obviously, it is DFS.
class Solution { public: vector<vector<string>> partition(string s) { vector<vector<string>> partition_set; vector<string> partition; partition_dfs(partition_set, partition, s, 0); return partition_set; } private: void partition_dfs(vector<vector<string>>& partition_set, vector<string>& partition, string& s, int start){ if(start == s.size()){ partition_set.push_back(partition); return; } for(int i = start + 1; i <= s.size(); i++){ string str = s.substr(start, i - start); if(is_parlindrome(str)){ partition.push_back(str); partition_dfs(partition_set, partition, s, i); partition.pop_back(); } } return; } bool is_parlindrome(string s){ int left = 0; int right = s.size() - 1; while(left < right){ if(s[left] != s[right]){ return false; } left++; right--; } return true; } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步