题解 | #放苹果#

放苹果

https://www.nowcoder.com/practice/bfd8234bb5e84be0b493656e390bdebf

本题考查递归,简化问题成子问题,要么少放一个盘子里,要么就每个盘子都放一个先。注意没有苹果也可以算一种情况,

#include <iostream>
using namespace std;

int plans(int apples, int plates){
    // 若无苹果或盘子,注意无苹果可分也算一种方案
    if(apples < 0 || plates <= 0)
        return 0;
    // 若只有一个苹果或只有一个盘子
    else if(apples == 1 || plates == 1)
        return 1;
    // 若苹果和盘子都多于1,那么该问题可以看作两个子问题的加和
    // 子问题1:一个盘子不放,放在其他盘子上
    // 子问题2:每个盘子放1个先
    else
        return plans(apples, plates-1) + plans(apples-plates, plates);
}

int main() {
    int apples, plates = 0;

    cin >> apples >> plates;

    int plan = plans(apples, plates);

    cout << plan << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

一只乌鸦:这不才9月吗,26到明年毕业前能一直找啊,能拿下提前批,转正的,offer打牌的都是有两把刷子的,为什么非要跟他们比。如果别人是9本硕+金牌+好几段大厂实习呢?如果别人是双非通天代呢?如果别人是速通哥呢?,做好自己就行了,我们做不到他们一样提前杀死比赛,但晚点到终点也没啥关系吧
双非应该如何逆袭?
点赞 评论 收藏
分享
09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务