全排列(递归)

版权声明:根号v587版权所有 https://blog.csdn.net/hcmdghv587/article/details/82531573
#include <iostream>
using namespace std;
const int NUM = 4;
void _swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}
void perm(int start, int length, int *a)
{
    if (start == length - 1)
    {
        for (int i = 0; i < length; i++)
            cout << a[i] << " ";
        cout << endl;
        return;
    }
    for (int i = start; i < length; i++)
    {
        _swap(a[start], a[i]);
        perm(start + 1, length, a);
        _swap(a[start], a[i]);
    }
}

int main()
{
    int a[NUM];
    for (int i = 0; i < NUM; i++)
        a[i] = i + 1;
    perm(0, NUM, a);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hcmdghv587/article/details/82531573