用DP解决最长子序列问题
来源:互联网 发布:3亿个精准客户数据库 编辑:程序博客网 时间:2024/06/06 03:03
“最长子序列”问题(即有限空间内,满足一定条件的最长顺序子序列)
一般的解法:用DP表来记录以当前节点为末节点的序列的解,这样可以固定问题的一端,以下以两个例子来讲子序列问题。
1.在一个整数数组中,找到最长的递增子序列。
分析:用DP表来记录以当前节点为末节点的序列的最大长度。maxLength[i]=max{maxLength[k],k=0~i-1and array[i]>array[k]}
参考解答:
#include <iostream>
#include <vector>
using namespace std;
int LongestIncreasingSubsquence(int arr[],int n)
{
vector<int> maxLength(n,1);
int global_max=0;
for(int i=0;i<n;i++)
for(int j=0;j<i;j++)
if(arr[i]>arr[j]&&maxLength[j]+1>maxLength[i])
maxLength[i]=maxLength[j]+1;
for(int i=0;i<n;i++)
if(global_max<maxLength[i])
global_max=maxLength[i];
return global_max;
}
int main()
{
int n;
cin>>n;
int arr[n];
int sum=0;
for(int i=0;i<n;i++)
cin>>arr[i];
sum=LongestIncreasingSubsquence(arr,n);
cout<<sum;
return 0;
}
2.在一个数组中找出一个连续的和最大的子数组
分析:只需要观察以当前节点为末节点的可能的最大sum,并使用max_sum记录。
sum[i]=max{sum[i-1]+arr[i],arr[i]}
参考代码:
#include "stdafx.h"
#include<iostream>
using namespace std;
int maxSum(int arr[],int n)
{
int max_sum=arr[0];
int sum=arr[0];
for(int i=1;i<n;i++)
{
if(sum+arr[i]>arr[i])
{
sum=sum+arr[i];
}else{sum=arr[i];}
if(max_sum<sum)
max_sum=sum;
}
return max_sum;
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[]={1,-2,3};
int max_sum=maxSum(arr,3);
cout<<max_sum;
system("pause");
return 0;
}
- 用DP解决最长子序列问题
- hdu 1160 DP 最长子序列问题
- 最长公共子序列问题 经典DP
- [dp]最长公共子序列问题
- DP---LCS 最长公共子序列问题
- 动态规划解决最长子序列问题
- 动态规划解决最长子序列问题
- 最长子序列问题
- 最长子序列问题
- 最长子序列问题
- 最长子序列问题
- 最长公共子序列--DP
- DP---最长公共子序列
- 最长公共子序列dp
- DP 最长公共子序列
- DP 最长公共子序列
- DP最长有序子序列
- 最长递增子序列 - dp
- Toolbar的常规设置(包括标题样式,菜单样式等)
- 数字加减多线程
- Rsync使用非ssh默认端口从远程服务器同步文件到本地
- [POJ1873]The Fortified Forest(dfs+凸包)
- Go语言:前后端对接
- 用DP解决最长子序列问题
- bat定时检测系统服务是否开启
- HDU 3315 My Brute(KM算法)
- STM32F4-IAP学习笔记(二)
- Mayan游戏
- BZOJ4644 经典傻逼题
- 那些年,被问过的Java面试题
- 1、Eclipse版本android 65535解决方案(原理等同android studio现在的分包方式)--Ant安装
- 1、Eclipse版本android 65535解决方案(原理等同android studio现在的分包方式)--Ant安装