题目:
类似求解三角数字的那个问题,可以采用递归的方法,但是用动态规划效率会比较高,而且可以不用写递归函数。子问题可以是b[N-1]~b[N]的最长上升自序列,不停地递归,直到b[1]~b[N]的最长上升子序列和,位置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