Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Combination Sum IIII in C++
Consider we have to generate all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used. Each combination should be a unique set of numbers. All numbers should be positive, and the solution must not contain duplicate combinations. So if k = 3 and n = 9, then the possible combinations are [[1,2,6],[1,3,5],[2,3,4]]
To solve this, we will follow these steps −
- Suppose we will solve this using forming a method called solve. This will be recursive method, this will take k, n, temp array, and start. the start is initially 1
- if n = 0
- if size of temp = k, then insert temp into res and return
- for i := start to minimum of 9 and n
- insert i into temp
- solve(k, n – i, temp, i + 1)
- delete the last element from temp
- The main method will be like
- create one blank vector called temp
- solve(k, n, temp)
- return res
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] << ", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
vector < vector <int> > res;
void solve(int k, int n, vector <int> temp, int start = 1){
if(n == 0){
if(temp.size() == k){
res.push_back(temp);
}
return;
}
for(int i = start ; i <= min(9, n); i++){
temp.push_back(i);
solve(k, n - i, temp, i + 1);
temp.pop_back();
}
}
vector<vector<int>> combinationSum3(int k, int n) {
res.clear();
vector <int> temp;
solve(k, n, temp);
return res;
}
};
main(){
Solution ob;
print_vector(ob.combinationSum3(2, 9));
}
Input
3 9
Output
[[1, 8, ],[2, 7, ],[3, 6, ],[4, 5, ],]
Advertisements