计算在游戏中达到给定分数的方法数


让我们考虑这样一个游戏,在这个游戏中,玩家可以在每次移动中通过 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

更新日期: 16-6-2020

581 次浏览

开启你的 事业

通过完成课程获得认证

开始
广告
© . All rights reserved.