C++ 最长上升子序列

基于动态规划的思想

#include
#include
#include
#include
#include
#include
using namespace std;

int main() {
	int arr[] = { 2,1,4,3,1,5,6};
	int len[8];  //数组各元素表示,以arr[i]为结尾的序列,递增子序列最长长度
	int max_val = 1;
	for (int i = 0; i < 8; i++) {
		len[i] = 1;//以本元素为结尾的序列,子序列最短的长度就是其本身的长度
		for (int j = 0; j < i; ++j) {  
			if (arr[j] < arr[i] && len[i] < len[j]+1)//当前面的元素小于结尾的元素时才有增加的可能
				len[i] = len[j] + 1;
		}
		max_val = max(max_val, len[i]);
	}
	cout<< max_val;

	return 0;
}

基于贪心+二分查找 

#include
#include
#include
#include
#include
#include
using namespace std;

int main() {
	vector arr{ 2,1,4,3,1,4,5,6 };
	vector len;  //数组各元素表示
	len.push_back(arr[0]);
	for (int i = 1; i < 8; ++i) {
		if (arr[i] > len.back())
			len.push_back(arr[i]);
		else if (arr[i] < len.back()) {
			int low = 0, high = len.size()-1;
			while (low <= high) {
				int mid = (low + high) / 2;
				if (len[mid] < arr[i]) {//寻找数组中第一个大于a[i]的数
					low = mid + 1;
				}
				else if (len[mid] >= arr[i]) {
					high = mid - 1;
				}
			}
			len[low] = arr[i];
		}
	}
	for (auto temp : len)
		cout << temp << " ";
	return 0;
}
#include
#include
#include
#include
#include
#include
using namespace std;

int main() {
	vector A{ 2,1,4,3,1,4,5,6 };
	vector len;  //数组各元素表示
	len.push_back(A[0]);
	for (int i = 1; i < 8; ++i) {
		if (A[i] > len.back())
			len.push_back(A[i]);
		else if (A[i] < len.back()) {
			auto it = lower_bound(len.begin(), len.end(), A[i]);//标准库中二分查找函数,返回第一个>=A[i]的位置
			if (it != len.end())
				*it = A[i];				
		}
	}
	for (auto temp : len)
		cout << temp << " ";
}

非严格递增子序列

#include
#include
#include
#include
#include
#include
using namespace std;

int main() {
	vector A{ 2,1,4,3,1,4,5,6 };
	vector len;  //数组各元素表示
	len.push_back(A[0]);
	for (int i = 1; i < 8; ++i) {
		if (A[i] > len.back())
			len.push_back(A[i]);
		else if (A[i] < len.back()) {
			auto it = upper_bound(len.begin(), len.end(), A[i]);//标准库中二分算法,返回第一个>A[i]的数
			if (it != len.end())
				*it = A[i];				
		}
	}
	for (auto temp : len)
		cout << temp << " ";
}

 

你可能感兴趣的:(C++算法)