矩阵中的最大路径和;礼物的最大价值--剑指offer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/langxue4516/article/details/79681550
/*!
 * @file     矩阵里面的最大路径和//礼物的最大价值.cpp
 * @Date:    2018/03/24 10:43
 * @author:  sicaolong
 * @Contact: sicaolong@163.com
 * @brief:   
 * @TODO: 
*/
#include<iostream>
#include <vector>
#include <assert.h>
using namespace std;

int get_the_max_sum1(vector<vector<int>>&a, int m, int n);
int get_the_max_sum2(vector<vector<int>>&a, int m, int n);
int max(int a, int b){ return a > b ? a : b; }
int main()
{
	vector<vector<int>>a;
	a=
	{
		{1,10,3,8},
		{12,2,9,6},
		{5,7,4,11},
		{3,7,16,5}
	};

	 int best_value1=get_the_max_sum1(a, 4, 4);
	cout<<best_value1<<endl;
	int best_value2 = get_the_max_sum2(a, 4, 4);
	cout << best_value2 << endl;
}
int get_the_max_sum1(vector<vector<int>>&a, int m, int n)
{
	vector<vector<int>>best(m+1,vector<int>(n+1));//best数组为5*5的数组;
	
	if (m < 0 || n < 0)
		return 0;
	//边界初始化为0;
	for (int i = 0; i < m; i++)
		best[i][0] = 0;
	for (int j = 0; j < n; j++)
		best[0][j] = 0;
	//状态转移,下一个状态跟当前状态的关系;best[i+1][j+1]表示下一个状态;
	for (int i = 0; i < m;i++)
		for (int j = 0; j < n; j++)
			best[i + 1][j + 1] = max(best[i + 1][j] + a[i][j], best[i][j + 1] + a[i][j]);
		//各个状态的输出
		for (int i = 0; i <= m; i++)
		{
			for (int j = 0; j <= n; j++)
				cout << best[i][j] << "   ";
			cout << endl;
		}
	return best[m][n];//最大值存储在best[4][4]
}
int get_the_max_sum2(vector<vector<int>>&a, int m, int n)
{
	vector<vector<int>>best(m + 1, vector<int>(n + 1));//best数组为5*5的数组;

	if (m < 0 || n < 0)
		return 0;
	//起始点进行初始化为a[0][0];
	best[0][0] = a[0][0];
	//边界的时候进行的状态转移
	for (int i = 1; i < m; i++)
		best[i][0] = best[i - 1][0] + a[i][0];
	for (int j = 1; j < n; j++)
		best[0][j] = best[0][j - 1] + a[0][j];
	//状态转移,当前状态仅仅跟前一个状态有关系;
	for (int i = 1; i < m; i++)
		for (int j = 1; j < n; j++)
		best[i][j] = max(best[i - 1][j] + a[i][j], best[i][j - 1] + a[i][j]);
	//各个状态的输出
		for (int i = 0; i < m;i++)
	{
		for (int j = 0; j < n; j++)
			cout << best[i][j] << "   ";
		cout << endl;
	}
	return best[m-1][n-1];//最大值存储在best[3][3]
	
}



展开阅读全文

没有更多推荐了,返回首页