
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find all combinations that add upto given number using C++
Suppose we have a positive number n. We have to find all combinations of positive numbers, that adds up to that number. Here we want only combinations, not the permutations. For the value n = 4, there will be [1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]
We will solve this using recursion. We have an array to store combinations, and we will fill that array using recursive approach. Each combination will be stored in increasing order of elements.
Example
#include<iostream> using namespace std; void getCombination(int arr[], int index, int num, int decrement) { if (decrement < 0) return; if (decrement == 0){ for (int i = 0; i < index; i++) cout << arr[i] << " "; cout << endl; return; } int prev; if(index == 0) prev = 1; else prev = arr[index-1]; for (int k = prev; k <= num ; k++) { arr[index] = k; getCombination(arr, index + 1, num, decrement - k); } } void findCombinations(int n) { int arr[n]; getCombination(arr, 0, n, n); } int main() { int n = 4; findCombinations(n); }
Output
1 1 1 1 1 1 2 1 3 2 2 4
- Related Questions & Answers
- Print all combinations of points that can compose a given number in C++
- Finding all possible prime pairs that sum upto input number using JavaScript
- Find square root of number upto given precision using binary search in C++
- How to find all the different combinations of opening and closing brackets from the given number k using C#?
- All combinations of strings that can be used to dial a number in C/C++?
- Find maximum number that can be formed using digits of a given number in C++
- Find all substrings combinations within arrays in JavaScript
- JavaScript function that generates all possible combinations of a string
- Python program to find all the Combinations in the list with the given condition
- Python program to find all the Combinations in a list with the given condition
- Program to find number of distinct combinations that sum up to k in python
- Find the slope of the given number using C++
- Print all combinations of factors in C++
- Sum all perfect cube values upto n using JavaScript
- C++ Program to Generate All Possible Combinations of a Given List of Numbers
Advertisements