算法趣题-Q23

一、问题描述

二、问题分析

        首先,每日一吐,这个题目的意思依旧让我陷入了理解误区,问题要求每次只能下注1枚硬币(理解成了可以一次下注多枚),其次,当24回合中途没有了硬币也会直接结束,并且不算在一种可能里。

        在以上限定条件下可以使用递归进行简易解题,当然可以使用内存优化方法,其中需要注意如果使用数组存储需要在数组大小上小心,使用递归的方式(C/C++实现)代码实现比较简单,但是对于回合数比较大的样例可能会有爆栈危险,故也可以将递归实现转换为递推实现(Python实现)。

三、代码实现

1.C/C++实现

#include <iostream>
#include <cstring>

using namespace std;

const int MAX_C = 10;
const int MAX_R = 24;

int counts[MAX_C + MAX_R + 1][MAX_R + 1];

int get_counts(int coins, int rounds)
{
	if (counts[coins][rounds] >= 0)
		return counts[coins][rounds];
	if (coins == 0)
		return counts[coins][rounds] = 0;
	if (rounds == 0)
		return counts[coins][rounds] = 1;
	return counts[coins][rounds] = get_counts(coins + 1, rounds - 1) + get_counts(coins - 1, rounds - 1);
}

int main()
{
	memset(counts, -1, sizeof(counts));
	cout << get_counts(MAX_C, MAX_R) << endl;
	return 0;
}

2.Python实现

# coding=utf-8

coins, rounds = 10, 24
counts = []


def generate(_coins, _rounds):
    counts.append([1] * (_coins + _rounds + 2))
    counts[0][0] = counts[0][-1] = 0  # 对边界设置为 0
    for i in range(_rounds):
        cur_round = [0]  # 边界
        for j in range(1, _coins + _rounds + 1):
            cur_round.append(counts[i][j - 1] + counts[i][j + 1])  # 根据上一层生成当前层
        cur_round.append(0)  # 添加边界
        counts.append(cur_round)


if __name__ == '__main__':
    generate(coins, rounds)
    print(counts[rounds][coins])
    pass

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值