动态规划问题(2)-最长上升子序列
2016-08-12 16:19
417 查看
题目:
![](http://img.blog.csdn.net/20160812160608904)
类似求解三角数字的那个问题,可以采用递归的方法,但是用动态规划效率会比较高,而且可以不用写递归函数。子问题可以是b[N-1]~b
的最长上升自序列,不停地递归,直到b[1]~b
的最长上升子序列和,位置k即为状态,状态的值即为到第k个位置的最长上升子序列长度。
状态转移方程可以是MaxLength[k] = max(left_MaxLength[i]) + 1,即第k个位置左边i个元素的最长上升子序列长度的和加1。
代码如下:
运行结果:
类似求解三角数字的那个问题,可以采用递归的方法,但是用动态规划效率会比较高,而且可以不用写递归函数。子问题可以是b[N-1]~b
的最长上升自序列,不停地递归,直到b[1]~b
的最长上升子序列和,位置k即为状态,状态的值即为到第k个位置的最长上升子序列长度。
状态转移方程可以是MaxLength[k] = max(left_MaxLength[i]) + 1,即第k个位置左边i个元素的最长上升子序列长度的和加1。
代码如下:
#include<iostream> #define MAX_NUM 10 using namespace std; int N; int MaxLength[MAX_NUM]; int longest_IncreSubStr(int arr[]) { int i,j,left_Max; MaxLength[1] = 1; for ( i = 1; i <= N; i++) { left_Max = 0;//记录第i个数为终点的左边数的最大上升子序列长度 for (j = 1; j < i; j++) { if (arr[i] > arr[j]) { if (left_Max < MaxLength[j]) left_Max = MaxLength[j]; } } MaxLength[i] = left_Max + 1; } int MaxSubLen = -1;//找到第i个元素左边最长上升子序列的最大值 for (i = 1; i <= N; i++) { if (MaxSubLen < MaxLength[i]) MaxSubLen = MaxLength[i]; } return MaxSubLen; } int main() { int i, j,arr[MAX_NUM]; cout << "Please input the numbers(N) of the array : " << endl; cin >> N; cout << endl; cout << "Please input the every digit of the array: " << endl; for (i = 1; i <= N; i++) { cin >> arr[i]; } cout << "Array is :" << endl; for (i = 1; i <= N; i++) { cout<<arr[i]; } cout << endl; cout << "The length of longest increasing substring is : " << longest_IncreSubStr(arr) << endl; return 0; }
运行结果:
Please input the numbers(N) of the array : 5 Please input the every digit of the array: 1 2 3 4 0 Array is : 12340 The length of longest increasing substring is : 4
相关文章推荐
- HDU 5371 Hotaru's problem
- java selenium Selenium IDE介绍及用法
- sqoop-1.99.6安装和测试
- HDU 5823 color II(状压DP)
- Makefile经典教程
- 第四章:Linear Models for Classification exercise 10-24
- Android多权限请求
- HP-UX执行脚本报错The specified value exceeds the user's allowable limit;Cannot create the specifie file
- mockito简单教程
- poj 3255 Roadblocks 次短路 spfa 解题报告
- Opencv中的3种线性滤波器
- java项目之——坦克大战 04
- 数据结构整理(二) 树
- Android时间戳转换为标准Datetime(yyyy-MM-dd hh:mm:ss)格式
- h5多图上传
- 【HDU3072】【JZOJ4686】通讯
- 定位 CLLocationManager
- 高德地图AMap_2DMap_V2.9.0_20160525版下,隐藏“高德地图”logo样式
- OJ-----提取不重复整数
- HDU 5093 Battle ships [二分图匹配] [匈牙利算法]