数字金字塔版本2

本文介绍了一个使用递归算法解决寻找从三角形顶部到底部的最大路径和的问题,通过C++实现,展示了如何定义搜索函数并遍历所有可能的路径来找到最大和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


sum作为状态,局部变量。

#include <iostream>
int N;
int mymax=0;
int tian[1000][1000];
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void search(int x,int y,int sum){
	 if(x==N){
	 	if (sum>mymax)
          mymax=sum;
		  return ;	 	
	 }
	 search(x+1,y,sum+tian[x+1][y]);
	 search(x+1,y+1,sum+tian[x+1][y+1]);
	
}
int main(int argc, char** argv) {
	cin>>N;
	
	for(int i=1;i<=N;i++)
	   for(int j=1;j<=i;j++)
	   {
	   	   cin>>tian[i][j];
	   }
	   search(1,1,tian[1][1]);
	
       cout<<mymax;	
  	return 0;
}

打印方案:

#include <iostream>
int N;
int mymax=0;
int tian[1000][1000];
int a[10000]={0};
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void search(int x,int y,int sum){
	 if(x==N){
	 	if (sum>mymax)
          mymax=sum;
          
          for(int i=1;i<=N;i++ )
	         cout<<a[i]<<" ";
	      cout <<endl << endl;   
          return ;
	    	  	 	
	 }
	 a[x+1]=tian[x+1][y];
	 search(x+1,y,sum+tian[x+1][y]);
	 a[x+1]=0;
	 
	 a[x+1]=tian[x+1][y+1];
	 search(x+1,y+1,sum+tian[x+1][y+1]);
	 a[x+1]=0;
}
int main(int argc, char** argv) {
	cin>>N;
	
	for(int i=1;i<=N;i++)
	   for(int j=1;j<=i;j++)
	   {
	   	   cin>>tian[i][j];
	   }
	   
	   a[1]=tian[1][1];
	   
	   search(1,1,tian[1][1]);
	 
       cout<<mymax;	
  	return 0;
}

把sum换成全局的变量


#include <iostream>
int N;
int mymax=0;
int tian[1000][1000];
int sum;
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void search(int x,int y){
	 if(x>N){
	 	if (sum>mymax)
          mymax=sum;
		  return ;	 	
	 }
	 sum = sum + tian[x][y];
	 search(x+1,y);	 	  
	 search(x+1,y+1);
	 sum = sum - tian[x][y];
	
}
int main(int argc, char** argv) {
	cin>>N;
	
	for(int i=1;i<=N;i++)
	   for(int j=1;j<=i;j++)
	   {
	   	   cin>>tian[i][j];
	   }
	   sum=0;
	   search(1,1);
	
       cout<<mymax;	
  	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值