【发布时间】:2016-07-15 07:50:34
【问题描述】:
我试图让任何数组的所有排列组合一次获取一定数量的元素,例如如果array = {1,2,3,4} 和r=3 则可能的排列将是24。这是我使用递归的实现,但这没有给出预期的结果。
void permutationUtil(vector<int> arr, vector<int> data, int start, int end, int index, int r) {
// Current permutation is ready to be printed, print it
if (index == r){
for (int j=0; j<r; j++)
printf("%d ", data[j]);
printf("\n");
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a permutation with remaining elements
// at remaining positions
for (int i = start; i <= end && end - i + 1 >= r - index; i++) {
data[index] = arr[i];
permutationUtil(arr, data, i + 1, end, index + 1, r);
}
}
void printPermutation(vector<int> arr, int n, int r) {
// A temporary array to store all permutation one by one
vector<int> data(n);
// Print all permutation using temprary array 'data[]'
permutationUtil(arr, data, 0, n - 1, 0, r);
}
【问题讨论】:
-
您在寻找
std::next_permutation吗? -
数组可能包含重复项吗?
-
@Arunmu std::next_permuation 对整个数组执行排列,一次取所有元素
-
@Jarod42 复制是不允许的。
-
@AshutoshPandey
std::next_permutation将迭代器作为输入。所以,应该由你决定。