全排列程序

本文介绍了一种使用递归实现的全排列算法。通过不断交换元素的位置来生成所有可能的排列组合,并详细展示了递归过程及其实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法:递归出口:集合中只有一个元素时,即exPos == setNum时,打印一个排列。
           继续递归条件:当exPos<setNum时,递归地产生前缀set[0:setNum-2],最后回到出口,结束递归。
过程中需要交换元素,把后面的元素依次与第一个元素交换,这样就可以第次只处理后setNum-1个元素,而
依次递归,就可以最终到达exPos==setNum的出口条件。

#include <iostream>


using namespace std;

//list is the whole set.
//exPos is the position to exchange with the first element.
//the numbers of the whole set.
void  wholeArrage(char* list, int exPos, int setNum);
inline void Swap(char& c1, char& c2);

int main()
{
    char set[] = {'a', 'b','c'};
    int setNum = 3;

    wholeArrage(set, 0, setNum);
    return 0;
}

void wholeArrage(char* list, int exPos, int setNum)
{
static int count = 0;
if (exPos == setNum-1)
{
count ++;
for (int i = 0; i < setNum; i++)
    cout << list[i];
cout << " ";
if (count % 10 == 0)
    cout << endl;
}
else
{
for (int i = exPos; i < setNum; i++)
{
Swap(list[i], list[exPos]);
wholeArrage(list, exPos+1, setNum);
            Swap(list[i], list[exPos]);
}
}

}

inline void Swap(char& c1, char& c2)
{
char tmp = c1;
c1 = c2;
c2 = tmp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值