Skip to content

Instantly share code, notes, and snippets.

@codyhex
Created November 18, 2017 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codyhex/22438c1815bd4761a65e42747c2b78c5 to your computer and use it in GitHub Desktop.
Save codyhex/22438c1815bd4761a65e42747c2b78c5 to your computer and use it in GitHub Desktop.
makeCombinations created by Hexe - https://repl.it/@Hexe/makeCombinations
#include <iostream>
#include <vector>
using namespace std;
/***********************************************/
/* @Task: combination
* @Input: n: number range 1 to n; k is number takes
* @Return: list of lists
* @Example: leetcode 8.5
*/
/************************************************/
class Solution {
public:
vector<vector<int>> combine(int nums, int takes) {
vector<vector<int>> results;
vector<int> list;
// call the package with n staring at 1 and count = 0
DFS(nums, takes, 1, 0, list, results);
return results;
}
private:
static void DFS(int &nums, int& takes, int start, int count,
vector<int>& list, vector<vector<int>>& results) {
// Demonstration print outs
// for(auto j:list) { cout << j << ' '; }
// cout << endl;
// Termination Condition(TC) push this list back is it reaches the takes
if (count == takes) {
results.push_back(list);
// return here to avoid extending the branch
return;
}
// for each ele in nums, should be head once.
for (int i = start; i <= nums; ++i) {
// choose it
list.push_back(i);
DFS(nums, takes, i+1, count+1, list, results);
// not choose it
// pop the ele out so you can fill another one at the same location.
list.pop_back();
}
}
};
int main() {
auto result = Solution().combine(4, 2);
// cout << "*************************************" << endl;
for(auto list: result) {
for (auto ele: list) {
cout << ele << ' ';
}
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment