算法第七节(第1部分:从暴力递归到贪心策略)

#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
using namespace std;
//
//  test.h
//  test
//
//  Created by 吴珝君 on 2018/12/31.
//  Copyright  ©   2018年 闲着也是贤者. All rights reserved.
//
/************************************************************************/
/************************************************************************/
/* 
从暴力递归到动态规划
*/
/************************************************************************/
/************************************************************************/
/* 
*/
/************************************************************************/


class  Hanoi 
{
public:
	void hanoi(int N, string from, string help, string to)
	{
		if (N == 1)
		{
			cout<< " move " << N << " from " <<from <<" to " << to<<endl;
			return;
		}
		hanoi(N - 1, from, to, help);//怎么讲N-1移动到help
		cout<< " move " << N << " from " <<from <<" to " << to<<endl;
		hanoi(N -1, help, from, to);

	}

}; 
//不死神兔的问题
//母牛生母牛,母牛三年后也能生母牛,假设母牛不会死,求N年后母牛的数目
class cow
{
public:
	int getCount(int n)
	{
		
		return func(n);
	}
	int func(int n)
	{
		if (n == 1)
		{
			return 1;
		}
		if (n ==2)
		{
			return 2;
		}
		if (n == 3)
		{
			return 3;
		}
		
		return func(n- 1) + func(n -3);

	}
};
//打印一个字符串的所有子序列 包括空串
class PrintAllSubsequence
{
public:
	void PrintAllSub (vector<string> v)
	{
		string str ="";
		print(v, str, 0);
	}
private:
	void print(vector<string> v, string str,int i)
	{
		
		if ( i== v.size())
		{
			cout << str << endl;
			return;
		}
		print(v,str+v[i],i+1);
		print(v,str,i+1);

	}
};
//给你一个二维数组,二维数组中的每个数都是正数,从左下角走到
//右下角 将沿途的数字加起来,返回最小的路径和。
class MinPath
{
	//分两种情况,要么向下走,要么向右边走。
public:
	int getMinPath(vector<vector<int>> v)
	{
		

		return walk(v,0,0);
	}
private:
	int walk(vector<vector<int>> v, int i, int j)
	{
		//如果走到了右下角
		int maxrow = v.size() - 1 ;
		int maxcol = v[0].size() -1 ;
		if (i == maxrow && j == maxcol)
		{
			return  v[i][j] ;
		}
		if (i == maxrow)
		{
		return	 v[i][j] + walk(v,i,1+j);
			
		}
		if (j == maxcol)
		{
		 return v[i][j] + 	walk(v,1+i,j);
		}
		int right = walk(v, 1+i, j );
		int down = walk(v, i, 1+j );
		return  v[i][j] + ((right > down) ? down : right);

	}
};
int main()
{
	Hanoi h;
	h.hanoi(4,"A","B","C");
	cow c;
	cout << c.getCount(4)<<endl;;
	vector<string>;
	vector<string> v;
	v.push_back("A");
	v.push_back("B");
	v.push_back("C");
	v.push_back("D");
	PrintAllSubsequence p;
	p.PrintAllSub(v);
	vector<vector<int>> vct;

	int m[4][4] = { { 1, 3, 5, 9 }, { 8, 1, 3, 4 }, { 5, 0, 6, 1 }, { 8, 8, 4, 0 } };
	for (int i =0; i <4 ; i++)
	{vector<int> t ;
	for(int j =0; j <4; j++)
		t.push_back(m[i][j]);
	vct.push_back(t);
	}
	MinPath m_;
	cout <<	m_.getMinPath(vct);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39804483/article/details/87833546