使用递归的策略生成所有的全排列
1. 生成所有的全排列_1 (数组元素初始化为0, 1, 2 ... n)
void perm_1(int *arr, int NLEN, int cur)
{
if (cur == NLEN){
for (int i = 0; i < NLEN; i++)
cout << arr[i] << '\t';
cout << endl;
return;
}
for(int i = cur; i < NLEN; i++){
swap(arr[cur], arr[i]);
perm_1(arr, cur+1);
swap(arr[cur], arr[i]);
}
}
2. 生成所有的全排列_2 (暴力法,数组元素初始化为0)
void perm_2(int *arr, int NLEN, int cur)
{
if (cur == -1){
for (int i = 0; i < NLEN; i++)
cout << arr[i] << '\t';
cout << endl;
return;
}
for (int i = 0; i < NLEN; i++)
if (arr[i] == 0){
arr[i] = cur;
perm_2(arr, cur-1);
arr[i] = 0;
}
}
3. 随机生成一个[1...n]的全排列
for (int i = 0; i < n; i++){
swap(arr[i], arr[rand()%(n-i) + i]);
}