一、问题描述
二、问题分析
首先,每日一吐,这个题目的意思依旧让我陷入了理解误区,问题要求每次只能下注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