用 C++ 列印所有可以組成給定數字的分數組合


在此問題中,我們給出了總分 n。打印出所有總分 n 的籃球分數組合,分數包括 1、2 和 3。

讓我們看一個例子來理解這個問題,

Input: 4
Output:
1 1 1 1
1 1 2
1 2 1
1 3
2 1 1
2 2
3 1

為了解決這個問題,我們將使用遞迴。並且為剩餘值 n-s(其中 s 是分數)修復資源。如果組合加起來為 n,則列印該組合。

示例

該程式碼展示了我們的程式碼實現 -

 動態演示

#define MAX_POINT 3
#define ARR_SIZE 100
#include <bits/stdc++.h>
using namespace std;
void printScore(int arr[], int arr_size) {
   int i;
   for (i = 0; i < arr_size; i++)
      cout<<arr[i]<<" ";
   cout<<endl;
}
void printScoreCombination(int n, int i) {
   static int arr[ARR_SIZE];
   if (n == 0) {
      printScore(arr, i);
   }
   else if(n > 0) {
      int k;
      for (k = 1; k <= MAX_POINT; k++){
         arr[i]= k;
         printScoreCombination(n-k, i+1);
      }
   }
}
int main() {
   int n = 4;
   cout<<"Different compositions formed by 1, 2 and 3 of "<<n<<" are\n";
   printScoreCombination(n, 0);
   return 0;
}

輸出

Different compositions formed by 1, 2 and 3 of 4 are
1 1 1 1
1 1 2
1 2 1
1 3
2 1 1
2 2
3 1

更新時間: 2020 年 1 月 22 日

175 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.