排列向量
Permutating a vector
我试图获取向量的每个排列,但也使用指示子排列的除法器。我的代码中似乎有一个错误,正如您可以从我的结果中看到结束排列。
0 1 3 2 |
和0 2 3 1 |
和0 3 2 1 |
都是重复的。
我也很好奇是否有一种方法可以做我正在尝试做的事情,可以接受对矢量的引用而不是制作副本。
IDEONE:http://ideone.com/fork/2v0wk3
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void permute(vector<int> v, int path_length) {
do {
for(int i=0; i<=3; ++i) {
cout << v[i] << " ";
if(i == path_length-1)
cout << "| ";
}
cout << endl;
if(path_length == v.size()) {
cout << "====="<< endl;
return;
}
permute(v, path_length+1);
} while(next_permutation(v.begin()+path_length-1,v.end()));
}
int main() {
vector<int> v;
for(int i=0;i<=3;++i)
v.push_back(i);
int path_length = 2;
permute(v, path_length);
return 0;
}
结果:
0 1 | 2 3
0 1 2 | 3
0 1 2 3 |
=====
0 1 3 | 2
0 1 3 2 |
=====
0 1 | 3 2
0 1 3 | 2
0 1 3 2 |
=====
0 2 | 1 3
0 2 1 | 3
0 2 1 3 |
=====
0 2 3 | 1
0 2 3 1 |
=====
0 2 | 3 1
0 2 3 | 1
0 2 3 1 |
=====
0 3 | 1 2
0 3 1 | 2
0 3 1 2 |
=====
0 3 2 | 1
0 3 2 1 |
=====
0 3 | 2 1
0 3 2 | 1
0 3 2 1 |
=====
预期成果:
0 1 | 2 3
0 1 2 | 3
0 1 2 3 |
=====
0 1 3 | 2
0 1 3 2 |
=====
0 2 | 1 3
0 2 1 | 3
0 2 1 3 |
=====
0 2 3 | 1
0 2 3 1 |
=====
0 3 | 1 2
0 3 1 | 2
0 3 1 2 |
=====
0 3 2 | 1
0 3 2 1 |
=====
考虑另一种方法来生成您需要的每个序列。我们将有一个vector <int> cur
来存储当前序列,以及一个vector <bool> used
来跟踪哪些整数被使用,哪些没有。在带有depth
参数的递归函数中,找到另一个未使用的整数,将其作为cur[depth]
,然后继续考虑下一个位置,即depth + 1
。只要深度在所需范围内,就打印结果。
#include <iostream>
#include <vector>
using namespace std;
int const n = 3;
void generate (vector <int> & cur, vector <bool> & used, int depth) {
if (depth >= 2) {
for (int i = 0; i < depth; i++) {
cout << cur[i] << ' ';
}
cout << endl;
}
for (int i = 0; i <= n; i++) {
if (!used[i]) {
used[i] = true;
cur[depth] = i;
generate (cur, used, depth + 1);
used[i] = false;
}
}
}
int main () {
vector <int> cur (n);
vector <bool> used (n, false);
cur[0] = 0;
used[0] = true;
generate (cur, used, 1);
return 0;
}
输出为:
0 1
0 1 2
0 1 2 3
0 1 3
0 1 3 2
0 2
0 2 1
0 2 1 3
0 2 3
0 2 3 1
0 3
0 3 1
0 3 1 2
0 3 2
0 3 2 1
您也可以添加=====
部件,如果您在depth > n
时打印它。
你的问题对我来说不是很清楚。您可以使用 STL 中不太为人所知的下一个排列:
std::vector<int> my_vector = { 1 , 5 , 7 , 2 , 3 , 10};
std::sort(my_vector.begin(), my_vector.end());
do {
std::copy(my_vector.begin(), my_vector.end(), ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
} while(std::next_permutation(my_vector.begin(), my_vector.end()));
1 - 对向量进行排序2 - 迭代排列(做,而只是打印它与副本到cout(
我不是在乎你所谓的"子"排列,你只是在每个排列中移动"|"吗?
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 写入向量<向量<bool>>
- 在向量C++中排列奇数和偶数
- 基于整数向量执行位排列的有效方法?
- 如何用单词排列向量中的每个字符升序?
- 使用向量的移动键盘排列(分段故障)
- 获得给定向量的排列索引列表的最佳方法是什么?
- Rcpp:按另一个向量的顺序重新排列一个向量
- 返回向量的所有排列的函数
- 如何将向量重新排列为列而不是行
- 如何使C++函数返回 char 数组所有排列的向量
- 排列解析器到向量<bool>,通过匹配
- 排序三个向量,基于一个的排列,有重复项
- 所有排列 c++ 与向量<int>和回溯
- 当我做排列时,一个向量的错误
- 按状态排列向量中的元素
- 如何对一对向量使用upper_bound,按对的递增顺序排列.第二,然后结对,第一
- 向量上的唯一排列
- 排列向量
- 使用向量的递归排列