c++ - 递归函数的执行顺序
问题描述
我最近尝试了这个问题:
一排排有
N
酒。每年你要么卖最左边的酒,要么卖最右边的酒。第- 年的i
酒有初始价格arr[i]
和第 - 年y*arr[i]
的价格y
。最大可能的总利润是多少?
我能够使用递归正确解决问题,但我无法理解程序的执行顺序。
代码是:
#include<iostream>
using namespace std;
int func(int arr[],int n,int l, int r, int y){
if(y>n)
return 0;
if(l>n-1)
return 0;
if(r<0)
return 0;
cout<<"l is: "<<l<<" and r is: "<<r<<endl;
int sum=max(arr[l]*y+func(arr,n,l+1,r,y+1), arr[r]*y+func(arr,n,l,r-1,y+1));
return sum;
}
int main()
{
int n=0;
cin>>n;
int arr[n];
for (int i = 0; i < n; ++i){
cin>>arr[i];
}
cout<<func(arr,n,0,n-1,1);
return 0;
}
对于输入n= 5
&values= 2,4,6,2,5
输出是:
l is: 0 and r is: 4
l is: 0 and r is: 3
l is: 0 and r is: 2
l is: 0 and r is: 1
l is: 0 and r is: 0
l is: 1 and r is: 1
l is: 1 and r is: 2
l is: 1 and r is: 1
l is: 2 and r is: 2
l is: 1 and r is: 3
l is: 1 and r is: 2
l is: 1 and r is: 1
l is: 2 and r is: 2
l is: 2 and r is: 3
l is: 2 and r is: 2
l is: 3 and r is: 3
l is: 1 and r is: 4
l is: 1 and r is: 3
l is: 1 and r is: 2
l is: 1 and r is: 1
l is: 2 and r is: 2
l is: 2 and r is: 3
l is: 2 and r is: 2
l is: 3 and r is: 3
l is: 2 and r is: 4
l is: 2 and r is: 3
l is: 2 and r is: 2
l is: 3 and r is: 3
l is: 3 and r is: 4
l is: 3 and r is: 3
l is: 4 and r is: 4
64
由于多个参数,我无法想象递归在做什么。请解释递归如何开始执行,以及如何可视化使用更多参数的递归。
解决方案
首先,没有定义 C++ 中的参数评估顺序。请参阅:https : //en.cppreference.com/w/cpp/language/eval_order 在您的情况下,max 的参数是从右到左评估的。
首先,您使用初始参数调用函数:
l = 0 , r = n-1, y = 1
到达语句
int sum=max(arr[l]*y+func(arr,n,l+1,r,y+1), arr[r]*y+func(arr,n,l,r-1,y+1));
时,评估右侧并调用函数 for func(arr,n,0,r-1,y+1)
。因为最右边的元素在 y 年被拾取,现在最右边的元素现在位于 index r-1
。当您在 year 中y+1
再次调用函数时,最右边的函数被调用r-2
and y+2
and r-3
andy+3
等等,直到您在递归中遇到基本情况。
当 r 等于 -1 时,该函数第一次达到基本情况。
l is: 0 and r is: 0
当 r 为 0 时打印。这意味着你做了:
int sum=max(arr[0]*y+func(arr,n,0+1,0,y+1), arr[0]*y+func(arr,n,0,-1,y+1));
然后要求右侧
func(arr,n,0,-1,y+n-1)
. 请注意, l 仍然为零,因为始终调用了递归的右侧。然后if(r<0)
case 返回函数。然后评估上一步的左侧。由于再次存在递归,直到l>n-1
每一步递增 l。
这称为深度优先搜索。
推荐阅读
- javafx - 如何使光标在 JavaFX 文本字段中可见?
- c++ - 如何检查整数中是否恰好设置了一位?
- java - Java:如何打印 s3 存储桶的内容
- java - 使用 SurfaceViewGL 快速过滤视频
- c# - 需要有关此列表逻辑的帮助,不确定如何编写?
- python-3.x - python中的列表索引超出范围错误,为什么会发生?
- typescript - 如果我所有的导入都来自我自己的文件,我是否需要使用 TypeScript 3.8 的“导入类型”功能?
- python - Pandas,在尝试拆分数据时收到“TypeError:'list' object is not callable”
- google-cloud-platform - 哪个网络浏览器可以让我们从 GCP 存储桶中重现 wav 音频文件?
- python - 加载时的Python进度条