atulsingh7890

Combination Sum III

Sep 12th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. // https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/555/week-2-september-8th-september-14th/3457/\
  2.  
  3. class Solution {
  4.     void find_combinations(int digits_required, int sum_remaining,int pos,std::vector<int> & c_vec) {
  5.         if(sum_remaining < 0 || digits_required < 0)
  6.             return;
  7.        
  8.         if(digits_required == 0 && sum_remaining == 0) {
  9.                 result.push_back(c_vec);
  10.         } else {
  11.             for(int i = pos; i <= 9; ++i  ) {
  12.                 c_vec.emplace_back(i);
  13.                 find_combinations(digits_required-1, sum_remaining - i, i+1, c_vec);
  14.                 c_vec.pop_back();
  15.             }
  16.         }
  17.     }
  18.  
  19.     std::vector<std::vector<int>> result;
  20. public:
  21.     vector<vector<int>> combinationSum3(int k, int n) {
  22.         std::vector<int> c_vec;
  23.        
  24.         find_combinations(k, n, 1, c_vec);
  25.         return result;
  26.     }
  27. };
Add Comment
Please, Sign In to add comment