放苹果

题目描述
把M个同样的苹果放在N个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法?(用K表示)5,1,1和1,5,1 是同一种分法。
输入

每个用例包含二个整数M和N。0<=m<=10,1<=n<=10。<=n<=10<=m<=10

样例输入
7 3

样例输出
8
方法一
深度搜索,时间复杂度O(mn),空间复杂度O(1)


class Solution {
public:
    int count(int m, int n){
        int cnt = 0, cntApple = 0;
        dfs(m, n, cnt, cntApple, 0,m);
        return cnt;
    }
    void dfs(const int m, const int n, int& cnt, int& cntApple, int nCnt,int preAppleNums){ 
        if (nCnt == n){
            if (cntApple == m)
                cnt++;      
            return;
        }
        for (int i = 0; i <= preAppleNums; i++){
            cntApple += i;
            dfs(m, n, cnt, cntApple, nCnt+1,i);
            cntApple -= i;
        }
    }
};

方法二
递归,时间复杂度O(mn),空间复杂度O(1)

int SharingApple(int m, int n)
{
    if(m == 1 || n == 1)
        return 1;
    if(m < n)
        return SharingApple(m , m);
    else if(m > n)
        return SharingApple(m, n-1) + SharingApple(m-n, n);
    else
        return 1 + SharingApple(m, n-1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值