我想要獲取任何數組的所有排列集合,例如如果array = {1,2,3,4}
和r=3
那麼可能的排列將是24
。這是我使用遞歸的實現,但是這並沒有給出預期的結果。所有的數組元素的排列在C++中一次獲取了一定數量的元素
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
可能數組包含重複? – Jarod42
@Arunmu std :: next_permuation在整個數組上執行排列,同時取得所有元素 –