博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode "Interleaving String"
阅读量:4610 次
发布时间:2019-06-09

本文共 2225 字,大约阅读时间需要 7 分钟。

I briefly took a look at:  And I got 1A :)

This is the best problem to understand DP deeper. At the very first sight to this problem statement, DP pattern may not be that obvious. Yes, DP is hard. But again, you should be able to figure out a DFS solution. So, please revise: what is the repeating computation pattern of the DFS solution? Right, s1[i] & s2[j] may be computed multiple times, when backtrace occurs in your DFS. And here comes the punch line of this problem:

DP pattern should address your enumeration\DFS repeating computation pattern! That's exactly the purpose of DP!

Here's the code:

class Solution {public:    bool isInterleave(string s1, string s2, string s3) {        size_t len1 = s1.length();        size_t len2 = s2.length();        size_t len3 = s3.length();        if ((len1 + len2) != len3) return false;        //    Init        vector
ret; ret.resize(len3 + 1); std::fill(ret.begin(), ret.end(), false); vector
> dp; // dp[i][j]: s1: len i, s2: len j -> valid? dp.resize(len2 + 1); for (int i = 0; i < len2 + 1; i++) { dp[i].resize(len1 + 1); std::fill(dp[i].begin(), dp[i].end(), false); } // Go DP: // dp[i + 1][j] = dp[i][j] ? (s[i + j] == s1[i]) : false // then, ret[i + j + 1] = dp[i + 1][j] for (int i = 0; i <= len1; i ++) for (int j = 0; j <= len2; j++) { if (i == 0 && j == 0) { dp[i][j] = true; ret[0] = true; continue; } if (i == 0) { dp[j][i] = dp[j - 1][i] && (s3[j - 1] == s2[j - 1]); } else if (j == 0) { dp[j][i] = dp[j][i - 1] && (s3[i - 1] == s1[i - 1]); } else { bool bi = dp[j - 1][i] && (s3[i + j - 1] == s2[j - 1]); bool bj = dp[j][i - 1] && (s3[i + j - 1] == s1[i - 1]); dp[j][i] = dp[j][i] | bi | bj; } ret[i + j] = ret[i + j] | dp[j][i]; } return ret[len3]; }};

转载于:https://www.cnblogs.com/tonix/p/3904425.html

你可能感兴趣的文章
Socket & TCP &HTTP
查看>>
osip及eXosip的编译方法
查看>>
Hibernate composite key
查看>>
[CF Round #294 div2] D. A and B and Interesting Substrings 【Map】
查看>>
keepalived+nginx安装配置
查看>>
我的2015---找寻真实的自己
查看>>
android编译遇到问题修改
查看>>
解决Ubuntu18.04.2远程桌面Xrdp登录蓝屏问题
查看>>
python_封装redis_hash方法
查看>>
《windows程序设计》获取窗口尺寸(05)
查看>>
【重点突破】——Canvas技术绘制音乐播放器界面
查看>>
监控级联时各个层的PoE交换机怎么选?
查看>>
存储过程
查看>>
ADO.NET--SqlConnection、SqlCommand的学习
查看>>
PCA降维处理
查看>>
random模块
查看>>
CSS3 新属性兼容性测试
查看>>
js闭包
查看>>
Oralce导入数据库出现某一列的值太大
查看>>
Union和Union All 的区别
查看>>