生成全排列示例

代码示例

#include <iostream>
#include <string>
using namespace std;

void fun1(string & list,int n , int index)
{
    if (index >= n)
    {
        cout << list << endl;
    }
    else
    {
        for (int i = index; i < n; i++)
        {
            swap(list[i] , list[index]);
            fun1(list , n , index + 1);
            swap(list[i] , list[index]);
        }
    }
}


void fun2(string & list , int n)
{
    if (n == 1)
    {
        cout << list << endl;
    }
    else
    {
        for (int i = 1; i <= n; i++)
        {
            fun2(list , n - 1);
            if (n % 2 == 1)
            {
                swap(list[0] , list[n - 1]);
            }
            else
            {
                swap(list[i - 1] , list[n - 1]);
            }
        }
    }
}


void fun3(string & str)
{   
    int left = 0;
    int right = 0;
    for (int i = str.length() - 1; i > 0; i--)
    {
        if(str[i - 1] < str[i]) 
        {
            left = i - 1;
            break;
        }
        if(i == 1)   
            return;
    }
    for (i = str.length() - 1; i > left; i--)
    {
        if(str[i] > str[left])
        {
            swap(str[left] , str[i]);
            break;
        }
    }

    left++;
    right = str.length() - 1;

    while(left < right)
    {
        swap(str[left++] , str[right--]);
    }

}

int factorial(int n)
{
    return n == 1 ? n : n * factorial(n - 1);
}



int main()
{
    //string list("123456");
    //fun1(list.length() , 0);
    //fun2(list.length());


    string str("123456");
    cout << str << endl;    
    for (int i = 1; i < factorial(str.length()); i++)
    {
        fun3(str); //按照字典序生成下一个排列
        cout << str << endl;
    }

    return 0;
}

1.找到使得 ai<ai+1 的最大 i //ai+1>ai+2>...>an
2.找到使得 ai<aj 的最大索引 j //j>=i+1
3.交换 ai aj // ai+1ai+2...an 仍保持降序
4.将 ai+1 an 的元素反序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值