字符串算法之 应用递归进行全排列

#include<iostream>
using namespace std;
char str[]="1234";
int size=sizeof(str)/sizeof(char); //size 的实际长度比str的长度多一位 
void fact(int from,int to)//from为起点,to为终点 
{
    if(from==to)
    {
        for(int i=0;i<=to;i++)
        {
            cout<<str[i];
        }
        cout<<'\n';
        return;
    }
    for(int i=from;i<=to;i++)
    {
        swap(str[i],str[from]);//将前后两位换位置 
        //第一次str[i]就是str[from],当进行第二次时就变成str[1]与str[0]进行交换了 
        fact(from+1,to);
        swap(str[i],str[from]);//将字符串变为原来的排列,即变为1234 
    }
 } 
 int main()
{
    fact(0,size-2);//根据字符串来说就是从str[0]到str[3],
    //size的实际长度为5,字符串的长度为4 
    return 0;
}

1.for循环虽然第一次进行交换时是自己换自己,但是进行第二次时是第i位与起始位置进行换位

2.通过在if条件语句里的for循环将换位后的每一项挨个输出

3.先是通过将第一位的数字或者字符确定,再将后边的进行递归,挨个进行,即完成

加油,算法终将学会!!!

posted @ 2019-06-17 19:43  袁潮  阅读(105)  评论(0编辑  收藏  举报