面试经常出现问题:
最大子序列:http://blog.csdn.net/yangquanhui1991/article/details/51943359
动态规划之最长递增子序列:http://blog.csdn.net/yangquanhui1991/article/details/51943000
动态规划之最长公共子串:http://blog.csdn.net/yangquanhui1991/article/details/51945211
动态规划之最长公共子序列:http://blog.csdn.net/yangquanhui1991/article/details/51942532
最大子序列是要找出由数组成的一维数组中和最大的连续子序列。比如{5,-3,4,2}的最大子序列就是 {5,-3,4,2},它的和是8,达到最大;而 {5,-6,4,2}的最大子序列是{4,2},它的和是6。你已经看出来了,找最大子序列的方法很简单,只要前i项的和还没有小于0那么子序列就一直向后扩展,否则丢弃之前的子序列开始新的子序列,同时我们要记下各个子序列的和,最后找到和最大的子序列。
#include <iostream>
#include <vector>
using namespace std;
int largestSub(vector<int>& vec, int& begin, int& end)
{
int maxSum = 0;
int currentSum = 0;
int newBegin = 0;
int len = vec.size();
for (int i = 0; i < len; i++)
{
currentSum += vec[i];
if (currentSum > maxSum)
{
maxSum = currentSum;
begin = newBegin;
end = i;
}
if (currentSum < 0)
{
currentSum = 0;
newBegin = i + 1;
}
}
return maxSum;
}
int main()
{
int len;
cout << "Input array length" << endl;
cin >> len;
cout << "Input an integer vector" << endl;
vector<int> arr;
int a;
for (int i = 0; i<len; ++i){
cin >> a;
arr.push_back(a);
}
int begin, end;
cout << largestSub(arr, begin, end) << endl;
for (int i = begin; i <= end; ++i)
cout << arr[i] << " ";
cout << endl;
system("pause");
return 0;
}