【LeetCode - 131】分割回文串(dp,dfs)
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode - 131】分割回文串(dp,dfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:https://leetcode-cn.com/problems/palindrome-partitioning/
題目:
給定一個字符串 s,將 s 分割成一些子串,使每個子串都是回文串。
返回 s 所有可能的分割方案。
示例:
輸入:?"aab"
輸出:
[
? ["aa","b"],
? ["a","a","b"]
]
解題報告:
先dp預處理出所有所有回文串,然后dfs就行了。如果沒要求輸出所有方案數,則依舊可以O(n^2) dp出方案數。
AC代碼:
class Solution { public:vector<vector<string>> ans;vector<string> tmp;int length;int dp[1005][1005];void dfs(int pos, string s) {if(pos == length+1) {ans.push_back(tmp);return ;}for(int i = pos; i<=length; i++) {if(dp[pos][i]) {tmp.push_back(s.substr(pos-1,i-pos+1));dfs(i+1,s);tmp.pop_back();}}}vector<vector<string>> partition(string s) {length = s.length();for(int l = 1; l<=length; l++) dp[l][l] = 1;for(int l = 1; l<length; l++) {if(s[l-1] == s[l]) dp[l][l+1] = 1;}for(int len = 3; len <= length; len++) {for(int l = 1; l+len-1<=length; l++) {int r = l+len-1;dp[l][r] = dp[l+1][r-1] && (s[l-1] == s[r-1]);}}dfs(1,s);return ans;} };?
總結
以上是生活随笔為你收集整理的【LeetCode - 131】分割回文串(dp,dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 外形神似Mate 40 华为畅享50 P
- 下一篇: B站上线首个付费视频后 UP主掉粉过万