ภาพรวมปัญหา
ได้รับคะแนนรวม n ต้องพิมพ์ชุดคะแนนบาสเกตบอล (1, 2, 3 แต้ม) ที่รวมกันได้ n ทุกชุดที่เป็นไปได้
ตัวอย่าง
Input: 4 Output: 1 1 1 1 1 1 2 1 2 1 1 3 2 1 1 2 2 3 1
วิธีแก้ปัญหา (Recursion)
ลองวางคะแนน 1, 2, 3 ตามลำดับ แล้วเรียกซ้ำหาค่าที่เหลือ (n - คะแนนที่วาง) จนครบ n
ตัวอย่างโค้ด C++
#define MAX_POINT 3
#define ARR_SIZE 100
#include <bits/stdc++.h>
using namespace std;
void printScore(int arr[], int arr_size) {
for (int 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) {
for (int 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;
}
ผลลัพธ์ (Output)
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