全排列Permutation递归方法

#include 

using namespace std;

void swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

void Permutation(int list[], int low, int high)
{
    if (low == high)//当low==high时,此时list就是其中一个排列,输出list
    {   
        for (int i = 0; i <= low; i++)
            cout << list[i];
        cout << endl;
    }
    else
    {
        for (int i = low; i <= high; i++)//每个元素与第一个元素交换
        {
            swap(list[i], list[low]);
            Permutation(list, low + 1, high); //交换后,得到子序列,用函数Permutation得到子序列的全排列
            swap(list[i], list[low]);//最后,将元素交换回来,复原,然后交换另一个元素
        }
    }
}

int main()
{
    int list[] = { 1, 2, 3 };
    Permutation(list, 0, 2);

    system("pause");
    return 0;
}

你可能感兴趣的:(全排列Permutation递归方法)