栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

算法趣题-Q23

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

算法趣题-Q23

一、问题描述

二、问题分析

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

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

三、代码实现 1.C/C++实现
#include 
#include 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/957792.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号