您的位置:首页 > 编程语言

最长递增子序列(编程之美2.16)

2014-04-13 00:21 176 查看
问题:给定一个序列 An =a1,a2,
... , 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;
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: