- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements