Print all combinations of points that can compose a given number in C++



In this problem, we are given the total score n. Print all combinations of basketball points that are 1, 2, and 3 that give a total score of n.

Let’s see an example to understand the problem,

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

To solve this problem, we will use recursion. And fix and resources for rest values n-s, where s is the score. If the combination adds up to n, print the combination.

Example

The code shows the implementation of our code −

 Live Demo

#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; }

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
Updated on: 2020-01-22T12:31:18+05:30

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements