// Source : https://oj.leetcode.com/problems/combinations/ // Author : Hao Chen // Date : 2014-07-03 /********************************************************************************** * * Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. * * For example, * If n = 4 and k = 2, a solution is: * * [ * [2,4], * [3,4], * [2,3], * [1,2], * [1,3], * [1,4], * ] * * **********************************************************************************/ #include #include #include #include #include #include using namespace std; void getCombination(int n, int k, vector& solution, vector< vector >& result ); vector > combine1(int n, int k); vector > combine2(int n, int k); vector > combine(int n, int k) { if (random()%2){ cout << "recusive method!" << endl; return combine1(n, k); } cout << "non-recusive method!" << endl; return combine2(n, k); } vector > combine1(int n, int k) { vector > result; vector solution; getCombination(n, k, solution, result); return result; } void getCombination(int n, int k, vector& solution, vector< vector >& result ){ if (k==0){ //sort to meet LeetCode requirement vector v = solution; sort(v.begin(), v.end()); result.push_back(v); return; } for(int i=n; i>0; i--){ solution.push_back(i); getCombination(i-1, k-1, solution, result); solution.pop_back(); } } vector > combine2(int n, int k) { vector > result; vector d; for (int i=0; i v; for(int x=0; x 0 ) ? 1 : 0; ones--; } break; } if (d[i]==1) ones++; } if (!found){ break; } } return result; } void printResult(vector >& result) { for(int i=0; i2){ n = atoi(argv[1]); k = atoi(argv[2]); } vector > r = combine(n, k); printResult(r); }