[英]Most efficient way to get all permutations in c++
我試圖用C ++計算很多組合。 我自己想出了以下工具,但效率並不理想。 獲得C-18-2(每2個組合18個)需要3秒多的時間,我相信這可以在更短的時間內完成。
vector<vector<int>> Mytool::combo2(int len){
MatrixXd ma = MatrixXd::Zero(len*len*len,2);
int ind = 0;
for (int i = 0 ;i<len;i++){
for (int j = 0 ;j<len;j++){
VectorXd v1(2);
v1<<i,j;
ma.row(ind) = v1;
ind++;
}
};
ind = 0;
vector<vector<int>> res;
for (int i=0;i<ma.rows();i++){
int num1 = ma(i,0);
int num2 = ma(i,1);
if (num1!=num2){
vector<int> v1;
v1.push_back(num1);
v1.push_back(num2);
sort(v1.begin(),v1.end());
if (find(res.begin(),res.end(),v1)==res.end())
res.push_back(v1);
}
}
return res;
}
任何提示或建議都會有所幫助。 先感謝您。
stl方式是使用std::next_permutation
std::vector<std::vector<int>> res;
std::vector<int> v(size - 2, 0);
v.resize(size, 1); // vector you be sorted at start : here {0, .., 0, 1, 1}.
do {
res.push_back(v);
} while (std::next_permutation(v.begin(), v.end()));
實例 。
正如Matthieu M指出的那樣,直接在do while循環中進行工作會更有效。
使用2個元素的組合時,一種更簡單的方法,您可以使用雙循環:
std::vector<std::vector<int>> res;
for (std::size_t i = 0; i != size; ++i) {
for (std::size_t j = i + 1; j != size; ++j) {
std::vector<int> v(size);
v[i] = 1;
v[j] = 1;
res.push_back(v);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.