C / C ++ longest increasing subsequence

Longest increasing sequence:

Given an array of length N, to find a longest sequence monotonically increasing, it is not necessarily continuous sequence, but not to collect the initial order.
For example: Given an array of length A 6 is {4, 5, 7, 3, 9}, then the longest monotonically increasing sequence {4,5,7,9} is a length of 4.
Dynamic programming ideas:
referred to d [i] is any one of the longest increment A [i] is the length of the end elements of the sub-sequence, find all located before than i and A [i] smaller elements A [j], At this time it may be
two situations:
(1) if found, for example, i = 2, this time a [i] = 7, the element is smaller than a [i] is a [0] = 4, a [1] = 5 taken all over a [i] smaller elements a [J], the corresponding d [j] of the most
large plus 1, i.e., d [i] = max {d [j]}, where j <i and a [J] <a [I];
(2) if not found, for example, i = 3, this time a [i] = 1, i is not present before the element is smaller than 1, then a [3] = 1 configuration alone incrementing a sequence, d [i] = 1.
Implementation:
When i = 0, the case A [0] = 4, only one element alone configuration sequence, then d [0] = 1;
when 1 i =, case A [1] = 5, ratio of a [1] is a small element a [0] = 4,
i.e., i = 1 corresponds to the length of the longest sequence should be incremented by 1, i.e., d [1] = d [0 ] + 1 = 2;
when i = 2 when, at this time a [2] = 7, ratio of a [2] of the light elements are j = 0,1, corresponding to a [0] = 4 and a [1] = 5, taking the corresponding d [j] maximum the d [1] = 2,
i.e., i = sequence length corresponding to the longest increasing shall d [2] = d [1 ] + 1 = 3 when 2;
When i = 3, this time A [3] = 1, i = 3 is not present until the element is smaller than 1,
i.e., d [3] = 1;
when i = 4, this time A [4] = 3, ratio of a [4] is smaller elements j = 3, a [3] = 1, this time corresponding to d [3] = 1, only one element, of course, to correspond to d [j] the largest,
i.e., i = 4 corresponding to the most long increasing subsequence length should be d [3] plus 1, i.e., d [4] = d [3 ] + 1 = 2;
when i = 5, the case A [5] = 9, the first five elements than a [5] is small, corresponding to the maximum take d [j] is, when j = 2, case d [2] = 3,
i.e. when i = 5 corresponding to the longest increasing subsequence length d [5] = d [2] + 1 = 4 .
Finally, through the array d, find the maximum number is the longest increasing subsequence

Implementation code:

int LargestListFind()
{
	int vec[6] = {4,5,7,1,3,9};
	int d[6] = {1};
	for(unsigned int i = 0; i < 6; i++)
	{
		d[i] = 1;
		for(unsigned int j = 0; j < i; j++)
		{
			if(vec[j] < vec[i] && d[j] >= d[i])
				d[i] = d[j] + 1;
		}
	}
	int Max = -1;
	for(unsigned int i = 0; i < 6; i++)
		if(Max < d[i])
			Max = d[i];
	return Max;
}
Published 54 original articles · won praise 17 · views 9168

Guess you like

Origin blog.csdn.net/qq_41979513/article/details/103192938