1. 程式人生 > >leetcode 97 Interleaving String

leetcode 97 Interleaving String

原題: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

Example 1:

Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac” Output: true Example 2:

Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc” Output: false

中文: 給你三個字串,s1,s2,s3,問你在保持s1和s2順序不變的情況瞎,能否使用s1和s2組合成s3.

程式碼:

class
Solution { public: bool dp[1000][1000]; string l,r,f; bool dfs(int x,int y) { if(x+y==f.size()) return true; if(dp[x][y]) return false; dp[x][y]=1; if(x<l.size()&&l[x]==f[x+y]&&dfs(x+1,y)) return true; if
(y<r.size()&&r[y]==f[x+y]&&dfs(x,y+1)) return true; return false; } bool isInterleave(string s1, string s2, string s3) { if(s1.size()+s2.size()!=s3.size()) return false; memset(dp,0,sizeof(dp)); l=s1,r=s2,f=s3; return
dfs(0,0); } };

解答: 和杭電的1501是一道題,用記憶化搜尋求解,使用dp[x][y]記錄s1和s2分別使用前x個字串和前y個字元是否使用過,防止回溯的過程中重複列舉,達到剪枝的效果。

此題題解居然有視訊講解,leetcode的網站太高階了!