试题:全排列

#include <iostream>
using namespace std;

#define NUM_COUNT 6

int count;            // 全排列个数
int num[NUM_COUNT];   // 给定全排列数据

void swap(int & a, int & b)
{
    if (a != b) {
        a ^= b;
        b ^= a;
        a ^= b;
    }
}

void init()
{
    count = 0;
    for (int i = 0; i < NUM_COUNT; i++) {
        num[i] = i + 1;
    }
}

void permute(int i)
{
    if (i < NUM_COUNT) {
        for (int j = i; j < NUM_COUNT; j++) {
            swap(num[i], num[j]);
            permute(i + 1);
            swap(num[i], num[j]);
        }
    }
    else {
        ++count;
        cout << " { ";
        for (int i = 0; i < NUM_COUNT; i++) {
            cout << num[i] << " ";
        }
        cout << "}" << endl;
    }
}

void permute()
{
    init();
    permute(0);
}

int main()
{
    permute();
    cout << "====== count = " << count << endl;
    return 0;
}

起初在实现permute的swap时:
我没有做if (a !=b)这个判断, 一般情况我们也没有必要这样做, 但是如果a和b是同一个元素时, a ^= b之后a变成了0, 因为a和b是同一个变量, 所以b也成了0, 之后再b ^= a; a ^= b; 最终出来时a和b所代表的元素变成了0

增加下利用STL提供的next_permutation/prev_permutation的实现:

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

void show(int num[], int length)
{
    for (int i = 0; i < length; ++i) {
        cout << num[i] << " ";
    }
    cout << endl;
}

int main()
{
    {
        cout << "-- test1 --" << endl;

        int count = 0;
        int num[] = {1, 2, 3, 4, 5, 6};
        int length = sizeof(num) / sizeof(num[0]);

        show(num, length);
        ++count;
        while (next_permutation(num, num + length, less<int>())) {
            show(num, length);
            ++count;
        }

        cout << "--- " << count << " ---" << endl;
    }

    getchar();

    {
        cout << "-- test2 --" << endl;

        int count = 0;
        int num[] = {6, 5, 4, 3, 2, 1};
        int length = sizeof(num) / sizeof(num[0]);

        show(num, length);
        ++count;
        while (next_permutation(num, num + length, greater<int>())) {
            show(num, length);
            ++count;
        }

        cout << "--- " << count << " ---" << endl;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值