标签:dp
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc"
,
s2 = "dbbca"
,
When s3 = "aadbbcbcac"
,
return true.
When s3 = "aadbbbaccc"
,
return false.
#include<iostream> #include<vector> #include<string> using namespace std; bool isInterleave(string s1, string s2, string s3) { int m = s1.size(); int n = s2.size(); if (s3.size()!=m+n) return false; vector<vector<bool>>InterVector(m+1,vector<bool>(n+1,false)); InterVector[0][0] = true; for (int i = 1;i!=m+1;++i) { if (s3[i-1]==s1[i-1]) InterVector[i][0] = true; else break; } for (int j = 1;j!=n+1;++j) { if (s3[j-1]==s2[j-1]) InterVector[0][j] = true; else break; } for (int i = 1;i!=m+1;++i){ char c1 = s1[i-1]; for (int j = 1;j!=n+1;++j) { char c2 = s2[j-1]; char c3 = s3[i+j-1]; if (c1==c3) InterVector[i][j] = InterVector[i-1][j]; if (c2==c3) InterVector[i][j] = InterVector[i][j-1]||InterVector[i][j]; } } return InterVector[m][n]; }
标签:dp
原文地址:http://blog.csdn.net/li_chihang/article/details/44779469