计算游戏中达到给定分数的方式
让我们考虑一个游戏,在这个游戏中,玩家可以在每个回合根据 3、5 或 10 分得分。还给出了目标分数。我们的任务是找出使用这三点达到目标分数的可能方式有多少种。
通过动态规划方法,我们将创建 0 到 n 的所有分数列表,并且对于 3、5、10 的每个值,我们只需更新表格。
输入和输出
Input: The maximum score to reach using 3, 5 and 10. Let the input is 50. Output: Number of ways to reach using (3, 5, 10)50: 14
算法
countWays(n)
仅有 3 种可能的分数,即 3、5 和 10
输入:n 是要达到的最高分数。
输出 −达到分数 n 的可能方式的数量。
Begin create table of size n+1 set all table entries to 0 table[0] := 1 for i := 3 to n, do table[i] := table[i] + table[i-3] done for i := 5 to n, do table[i] := table[i] + table[i-5] done for i := 10 to n, do table[i] := table[i] + table[i-10] done return table[n] End
示例
#include <iostream>
using namespace std;
// Returns number of ways to reach score n
int countWay(int n) {
int table[n+1], i; //table to store count for each value of i
for(int i = 0; i<=n; i++) {
table[i] = 0; // Initialize all table values as 0
}
table[0] = 1; //set for 1 for input as 0
for (i=3; i<=n; i++) //try to solve using 3
table[i] += table[i-3];
for (i=5; i<=n; i++) //try to solve using 5
table[i] += table[i-5];
for (i=10; i<=n; i++) //try to solve using 10
table[i] += table[i-10];
return table[n];
}
int main() {
int n;
cout << "Enter max score: ";
cin >> n;
cout << "Number of ways to reach using (3, 5, 10)" << n <<": " << countWay(n);
}输出
Enter max score: 50 Number of ways to reach using (3, 5, 10)50: 14
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP