Advertisement
Fastrail08

Combinations Sum 3 Leetcode

Jun 15th, 2025
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void getPossibleComb(int level, int n, int k, string path, vector<vector<int> > &combinations){
  5.     if(level > 9){
  6.         if(n == 0 && k == 0){
  7.             vector<int> integerPath;
  8.           for(char c : path){
  9.               integerPath.push_back(c - '0');
  10.           }
  11.           combinations.push_back(integerPath);
  12.       }
  13.    
  14.     return;
  15.     }
  16.    
  17.    
  18.     // use the number
  19.     if(k > 0 && n - level >= 0){
  20.         getPossibleComb(level + 1, n - level, k - 1, path + to_string(level), combinations);
  21.     }
  22.    
  23.     //don't use the number
  24.     getPossibleComb(level + 1, n, k, path, combinations);
  25.    
  26. }
  27.  
  28. int main() {
  29.     // your code goes here
  30.     int n, k;
  31.     cin >> n >> k;
  32.     vector<vector<int> > combinations;
  33.     getPossibleComb(1, n, k, "", combinations);
  34.     for(int i = 0; i < combinations.size(); i++){
  35.         for(int j = 0; j < combinations[i].size(); j++){
  36.             cout << combinations[i][j] << " ";
  37.         }
  38.         cout << '\n';
  39.     }
  40.  
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement