递归实现集合中元素的全排列。
R={r1,r2,r3,,rn}
归纳定义如下:
n = 1时,Perm(R) = (r1)
n > 1时,Perm(R) = (r1)Perm(R-r1) + (r2)Perm(R-r2) +,,,+ (rn)Perm(R-rn)
template<class Type>
void Perm(Type list[], int k, int m)
{if (k == m){for (int i = 0; i < m; i++)cout << list[i];cout << endl;}else{for (int i = k; i < m; i++){swap(list[k], list[i]);//交换两个值Perm(list, k + 1, m);swap(list[k], list[i]);}}
}
int main()
{int list[] = {1,2,3};Perm(list, 0, 3);return 0;
}
//输出1,2,3的全排列
/*
123
132
213
231
321
312*/