leetcode spring board

Title description There is a small ball falling on a series of continuous spring plates. After the ball falls on a certain spring plate, it will be bounced to a certain place until the ball is bounced to a place other than the spring plate. Assuming that there are n consecutive spring plates, each spring plate occupies a unit distance, and a[i] means that the iith spring plate will bounce the ball forward a[i] distance. For example, the spring at position 1 can move the ball forward 2 distances to reach position 3 . If the ball falls on a spring plate, it will be ejected from the spring plate after a series of bounces, and then the ball can be ejected from the spring plate. Now that the ball falls on the No. 11 spring plate, how many times will the ball be bounced before it will pop out of the spring plate. The No. 1 spring plate also counts once. c++ implementation

/*这是一个递归的C++程序,主要用来计算给定数组从当前位置开始到末尾的最小递归移动次数。这个移动方式非常特别,每次只能移动到数组中的下一个元素,并且移动的代价就是该元素的值。当到达数组末尾时,返回0。

函数f(i, arr, n)表示从数组的第i个元素开始,到数组的最后一个元素的最小递归移动次数。我们可以通过以下的方式进行递归计算:

如果i已经超过或者等于n(也就是数组的长度),那么说明已经到达了数组的末尾,此时返回0。
否则,我们需要从当前位置开始,移动到下一个位置,并且每次移动的代价是arr[i]。所以我们需要递归地计算从下一个位置开始,到数组末尾的最小递归移动次数,然后再加上当前位置的数量。
在主函数main()中,首先输入数组的长度n,然后输入n个整数,并将它们存入数组arr中。最后,调用函数f(0, arr, n),也就是计算从数组的第一个元素开始,到数组的最后一个元素的最小递归移动次数,并且输出结果。
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <stack>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
using namespace std;

// 定义一个函数f,接收三个参数:下标i、数组引用arr和数组长度n  
// 函数的功能是计算从下标i开始,通过移动每个元素一次能形成的最大高度  
int f(int i, vector<int> &arr, int n) {  
    // 如果i大于等于n,表示已经处理完所有元素,返回0  
    if (i >= n) return 0;  
    // 否则,继续处理下一个元素,并返回处理结果加1  
    return f(i + arr[i], arr, n) + 1;  
}  
  
// 主函数,程序的入口点  
int main() {  
    // 定义两个变量n和arr,分别表示数组长度和数组元素列表  
    int n;  
    vector<int> arr;  
    // 从标准输入读取一个整数n,表示数组的长度  
    cin >> n;  
    // 循环n次,每次读取一个整数并存入数组arr中  
    for (int i = 0, a; i < n; i++) {  
        cin >> a;  
        arr.push_back(a);  
    }  
    // 调用函数f计算从下标0开始能形成的最大高度,并输出结果  
    cout << f(0, arr, n) << endl;  
    // 返回0,表示程序正常退出  
    return 0;  
}

Guess you like

Origin blog.csdn.net/dsafefvf/article/details/132663676