행렬의 최대 경로와;선물의 최대 가치 - 검지offer

/*!
 * @file               //       .cpp
 * @Date:    2018/03/24 10:43
 * @author:  sicaolong
 * @Contact: [email protected]
 * @brief:   
 * @TODO: 
*/
#include
#include 
#include 
using namespace std;

int get_the_max_sum1(vector>&a, int m, int n);
int get_the_max_sum2(vector>&a, int m, int n);
int max(int a, int b){ return a > b ? a : b; }
int main()
{
	vector>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<>&a, int m, int n)
{
	vector>best(m+1,vector(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>&a, int m, int n)
{
	vector>best(m + 1, vector(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]
	
}



좋은 웹페이지 즐겨찾기