递归算法计算n各元素的排列

[ 789 查看 / 0 回复 ]

#include <iostream>
using namespace std;
template <class T>
void Perm(T list[], int k, int m)
{
        int i;
        if (k == m)    // output a arrange
        {
                for (i = 0; i <= m; i++)
                        cout << list;
                cout << endl;
        }
        else    // recurse
        {
                for (i = k; i <= m; i++)
                {
                        Swap(list[k], list);
                        Perm(list, k+1, m);
                        Swap(list[k], list);
                }
        }
}
template <class T>
inline void Swap(T& a, T& b)    // swap the item
{
        T temp = a; a = b; b = temp;
}
int main()
{
        //char set[4] = "abc";
        int set[3] = {1,2,3};
        cout << "the arrange of " << set << ":" << endl;
        Perm(set, 0, 2);
        return 1;
}
TOP
凌阳教育嵌入式培训