Created
March 18, 2017 06:27
-
-
Save qnnnnez/76d0ba6fe8240f0d5879fd25856037a2 to your computer and use it in GitHub Desktop.
全组合 in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
#include <iostream> | |
using namespace std; | |
int combinations(int n, int k) | |
{ | |
int result = 1; | |
for (int i = n - k + 1; i <= n; ++i) | |
{ | |
result *= i; | |
} | |
for (int i = 2; i <= k; ++i) | |
{ | |
result /= i; | |
} | |
return result; | |
} | |
vector<vector<int> > all_combination(int all, int select) | |
{ | |
if (select == 1) | |
{ | |
vector<vector<int> > result(all); | |
for (int i = 0; i < all; ++i) | |
{ | |
result[i] = { i }; | |
} | |
return result; | |
} | |
else | |
{ | |
vector<vector<int> > result; | |
result.reserve(combinations(all, select)); | |
for (int i = 0; i < all - select + 1; ++i) | |
{ | |
vector<vector<int> > t = all_combination(all - i - 1, select - 1); | |
for (auto it = t.begin(); it != t.end(); ++it) | |
{ | |
vector<int> c; | |
c.reserve(it->size() + 1); | |
c.push_back(i); | |
for (auto jt = it->begin(); jt != it->end(); ++jt) | |
{ | |
c.push_back(i + 1); | |
} | |
result.push_back(move(c)); | |
} | |
} | |
return result; | |
} | |
} | |
int main() | |
{ | |
vector<vector<int> > a = all_combination(10, 3); | |
for (vector<int> t : a) | |
{ | |
for (int x : t) | |
cout << x << ", "; | |
cout << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment