博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
从一道算法题说去1
阅读量:6659 次
发布时间:2019-06-25

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

声明:算法学习来自,7月算法,面试&算法&机器学习&找工作就上七月算法

1. 今天学习的算法是 LCS,最长公共子序列,属于典型的动态规划基础题。

    十分钟搞定LCS 学习视频:http://julyedu.com/video/play/id/9

2. 实践代码:

/*Algorithm LCS*/#include 
#include
#include
#include
#include
using namespace std;#define MAX 50// Get LCSint GetLcs(int dp[][MAX], int path[][MAX], const string& strOne, const string& strTwo) { int strOneLength = strOne.length(); int strTwoLength = strTwo.length(); for (int i = 0; i < strOneLength; ++i) { dp[i][0] = 0; } for (int i = 0; i < strTwoLength; ++i) { dp[0][i] = 0; } for (int i = 0; i < strOneLength; ++i) { for (int j = 0; j < strTwoLength; ++j) { if (strOne[i] == strTwo[j]) { dp[i+1][j+1] = dp[i][j] + 1; path[i+1][j+1] = 0; //leftTop } else { if (dp[i][j+1] > dp[i+1][j]) { dp[i+1][j+1] = dp[i][j+1]; path[i+1][j+1] = -1; //top } else { dp[i+1][j+1] = dp[i+1][j]; path[i+1][j+1] = 1; //left } } } } return dp[strOneLength][strTwoLength];}// Print LCS stringstring PrintLcs(int path[][MAX], const string& strOne, const string& strTwo) { stack
stk; int i = strOne.length(); int j = strTwo.length(); while ((i > 0) && (j > 0)) { if (path[i][j] == 0) { stk.push(strOne[i-1]); --i; --j; } else if (path[i][j] == 1) { --j; } else { --i; } } string lcsString = ""; while (!stk.empty()) { lcsString = lcsString + stk.top(); stk.pop(); } return lcsString;}int main(int argc, char **argv) { string strOne = "bdcaba"; string strTwo = "abcbdab"; int dp[MAX][MAX], path[MAX][MAX]; cout << GetLcs(dp, path, strOne, strTwo) << endl; cout << PrintLcs(path, strOne, strTwo) << endl; return 0;}

转载地址:http://gyato.baihongyu.com/

你可能感兴趣的文章
ASP.NET Atlas学习团队建议收集
查看>>
云安全趋势:IaaS?谢了,我要 PaaS
查看>>
Silverlight/Windows8/WPF/WP7/HTML5周学习导读(6月25日-7月1日)
查看>>
【java】【转】Java之classpath
查看>>
cocos2dx - Lua 语言
查看>>
漂亮好用的ASP.NET图表控件 免费的
查看>>
又谈“装系统”
查看>>
颈椎病,大部分IT人的痛
查看>>
MyEclipse 快捷键
查看>>
[Cocos2d-x For WP8]ActionManager动作管理
查看>>
黄聪:Wordpress 模版技术手册 - WordPress Theme Technical manuals
查看>>
TextView及其子类
查看>>
Silverlight WCF RIA服务(三十四)身份验证、角色、个性化 5
查看>>
Yii “CDbConnection failed to open the DB connection: could not find driver"解决办法
查看>>
WCF4.0进阶系列--第四章 保护企业内部的WCF服务(转)
查看>>
IOS4.x下UIWebView的显示问题
查看>>
提升Visual Studio 2012的响应能力
查看>>
template<class T>函数模板
查看>>
POJ——2546
查看>>
SQL中的关联更新和关联删除
查看>>