最长递增子序列(编程之美2.16)
2014-04-13 00:21
176 查看
问题:给定一个序列 An =a1,a2,
... , an,找出最长的子序列使得对所有i
< j,ai <aj。
1.用动态规划实现——求最长的子序列长度
测试代码
... , an,找出最长的子序列使得对所有i
< j,ai <aj。
1.用动态规划实现——求最长的子序列长度
int longestIncreaseSubSerial(int* array, int length) { if (NULL == array || 0 >= length) { return -1; } //初始化各个子序列的最大长度 int* currentMax = new int[length]; for (int i = 0; i < length; ++i) { currentMax[i] = 1; } for (int i = 0; i < length; ++i) { for (int j = 0; j < i; ++j) { if (array[j] < array[i]) { //递归关系式——如果a[k+1]>a[i],longest[k+1]=max{longest[i]}+1(i=0,1,...,k),否则其等于1. currentMax[i] = std::max(currentMax[j] + 1, currentMax[i]); } } } int longest = 0; for (int i = 0; i < length; ++i) { longest = std::max(longest, currentMax[i]); } delete currentMax; return longest; }
测试代码
/* * longestCommomSerialMain.cpp * * Created on: 2014-4-11 14:40:08 * Author: danDingCongRong */ #include<iostream> using namespace std; //输入各个数组元素 void inputArray(int* array, int length) { cout << "输入这个数组中的各个数字:" << endl; for (int i = 0; i < length; ++i) { cin >> array[i]; } } int main() { int length = 0; cout << "请输入数组的长度:" << endl; while (cin >> length) { int* x = new int[length]; inputArray(x, length); cout << "longest=" << longestIncreaseSubSerial(x, length) << endl; delete x; cout << "请输入数组的长度:" << endl; } return 0; }
相关文章推荐
- 求数组中的最长递增子序列(编程之美2.16)
- 最长递增子序列(编程之美)
- 编程之美 求数组中的最长递增子序列
- 编程之美2.16-最长递增子序列(Longest Subsequence)
- 回文字符序列(编程之美2015资格赛)
- 回文字符序列——微软编程之美2015资格赛第2题题解
- 2015编程之美资格赛题目2 : 回文字符序列
- 编程之美2.16求数组中最长递增子序列Java版
- 最长递增子序列 O(NlogN)算法
- 编程之美 set 7 求数组中的最长递增子序列
- 最长递增子序列 O(NlogN)算法
- 最长递增子序列
- 最长递增子序列的三种算法
- 动态规划求最长递增子序列
- 最长递增子序列模板
- 最长递增子序列O(NlogN)算法
- 最长递增子序列
- 最长递增子序列(LIS)-动态规划
- 最长递增子序列
- 最长递增子序列-动态规划(引用编程之美)