使用 C++ 計算達到指定分數的方案數(只能使用 1 或 2 分,且不能連續使用 2 分)


給定一個得分。目標是以一種方式達到該得分,即擊球手每次擊球只能獲得 1 分或 2 分。限制條件是不能連續獲得 2 分。例如,要達到給定的得分 6,可以獲得分數的方式如下:1+2+1+2,但不能是 2+2+1+1 或任何其他包含兩個連續 2 的方式。

例如

輸入

score=4

輸出

Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 4

解釋

The ways in which we can reach the score 4 in following ways:
1+1+1+1, 1+1+2, 1+2+1, 2+1+1

輸入

score=5

輸出

Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 6

解釋

The ways in which we can reach the score 6 in following ways:
1+1+1+1+1, 2+1+1+1, 1+2+1+1 , 1+1+2+1, 1+1+1+2, 2+1+2

以下程式中使用的方案如下

在這種方案中,我們將使用一個標誌來標記前一個得分是否為 2,如果前一個得分是 2,我們將用下一個得分 1 來覆蓋該得分,否則用 2 來覆蓋。

  • 取一個整數變數 score。

  • 取標誌變數 check,初始值為 false。

  • 函式 ways_reach_score(int score, bool check) 用於計算使用 1 和 2 且不連續使用 2 來達到指定分數的方案數。

  • 將初始計數設定為 0。

  • 如果分數為 0,則返回 0。

  • 如果 check 為 false,表示前一個得分是 1,因此,如果當前分數大於 0,則方案數將為 count = ways_reach_score(score − 1, false) + ways_reach_score(score − 2, true)。

  • 否則,前一個得分是 2,因此後續得分只能是 1,所以方案數將為 ways_reach_score(score − 1, false)。

  • 最後,我們將得到總方案數 count。

  • 返回 count 作為結果。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int ways_reach_score(int score, bool check){
   int count = 0;
   if (score == 0){
      return 1;
   }
   if (check == false && score > 1){
      count += ways_reach_score(score − 1, false) + ways_reach_score(score − 2, true);
   } else {
      count += ways_reach_score(score − 1, false);
   }
   return count;
}
int main(){
   int score = 4;
   bool check = false;
   cout<<"Count of ways to reach a score using 1 and 2 with no consecutive 2s are: "<<ways_reach_score(score, check);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count of ways to reach a score using 1 and 2 with no consecutive 2s are: 4

更新於: 2021年1月5日

165 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.