最长递增子序列dp_使用动态编程(DP)的最长递增子序列

最长递增子序列dp

Problem: You are given an array of length N. You have to find the longest increasing subsequence.

问题:给您一个长度为N的数组。 您必须找到最长的递增子序列

Constraints: 1 <= N <= 10^4

限制条件: 1 <= N <= 10 ^ 4

    Sample inputs:
    6
    10 1 3 8 81 67

    Sample output:
    4

Explanation of the problem:

问题说明:

We have to find the length of longest increasing subsequence. In sample input the longest increasing subsequence is 1,3,8,67 so length of this is 4.

我们必须找到最长的递增子序列的长度。 在样本输入中, 最长的递增子序列1,3,8,67,因此其长度为4

Solution:

解:

Before going to the code we can see that recursive solution will show time limit exceeded. As recursive solution has time complexity as O(2^(N)). So we definitely have to use DP. I will be using a 1D- array in which ith cell represents the length of longest increasing subsequence up to ith index in the original array.

在转到代码之前,我们可以看到递归解决方案将显示超出时间限制。 由于递归解的时间复杂度为O(2 ^(N)) 。 因此,我们绝对必须使用DP。 我将使用一维数组,其中 i 单元格代表最长递增子序列长度,直到原始数组中的 i 索引。

So now is the code of above approach:

现在是上述方法的代码:

#include <iostream>
using namespace std;

int LIS(int arr[], int n){
	int dp[n] = {0};
	dp[0] = 1;
	for (int col = 1; col < n; col++) {
		int max = 0;
		for (int i = 0; i < col; i++) {
			if (arr[i] < arr[col]) {
				if (max < dp[i]) {
					max = dp[i];
				}
			}
		}
		dp[col] = max+1;
	}
	int max1 = -1000000;
	for(int value : dp) {
		if(max1<value) {
			max1 = value;
		}
	}
	return max1;
}

int main() {
	int n;
	cin >> n;
	int arr[n];
	for(int i = 0;i<n;i++){
		cin >> arr[i];
	}
	cout << LIS(arr, n) << endl;
	return 0;
}

Output

输出量

6
10 1 3 8 81 67
4  

Though I am using a linear array to store the arrays time complexity is O(N^2). It is not necessary that the dimension of the matrix is the time complexity of the program in the dynamic programming approach.

虽然我使用线性数组存储数组,但时间复杂度为O(N ^ 2) 。 在动态编程方法中,矩阵的维数不必是程序的时间复杂度。

翻译自: https://www.includehelp.com/algorithms/longest-increasing-subsequence-using-dynamic-programming-dp.aspx

最长递增子序列dp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值