递归

11  •  1个月前


#include <iostream>
using namespace std;

int countReachableApples(int apple_heights[], int index, int max_reach_height, int max_height_with_bench) {
    // 递归终止条件:当所有苹果都检查完毕
    if (index == 10) {
        return 0;
    }

    // 当前苹果能被摘到
    if (apple_heights[index] <= max_height_with_bench) {
        return 1 + countReachableApples(apple_heights, index + 1, max_reach_height, max_height_with_bench);
    }

    // 当前苹果不能被摘到,递归检查下一个苹果
    return countReachableApples(apple_heights, index + 1, max_reach_height, max_height_with_bench);
}

int main() {
    int apple_heights[10];
    int max_reach_height;
    int bench_height = 30;

    // 读取10个苹果的高度
    for (int i = 0; i < 10; ++i) {
        cin >> apple_heights[i];
    }

    // 读取陶陶的最大伸手高度
    cin >> max_reach_height;

    // 计算陶陶站在板凳上后的最大可达高度
    int max_height_with_bench = max_reach_height + bench_height;

    // 使用递归计算陶陶能够摘到的苹果数量
    int reachable_count = countReachableApples(apple_heights, 0, max_reach_height, max_height_with_bench);

    // 输出结果
    cout << reachable_count << endl;

    return 0;
}


评论:

大佬方法太好了,看一遍就懂了


lzhh_lzhh26  •  1个月前

大佬风范,一遍就懂


天生我材必有难,千金散尽还债来  •  1个月前

大佬的方法太简单了,一学就会


6  •  1个月前

请先登录,才能进行评论