剑指offer 28字符串全排列

思路1.当前字符依次与后面的字符交换形成新的排列

void permutation(char*str,char*start)
{
    if(*(start+1)=='\0')
    {
        cout<<str<<endl;
    }
    else
    {
        for(char*p=start;*p!='\0';++p)
        {
            cswap(p,start);
            permutation(str,start+1);
            cswap(p,start);
        }
    }
}


思路2.DFS,标记每个字符是否访问过,把访问的字符存起来,最后输出。

int visit[128]={0};
char stackk[128]={0};
void DFS(int s,int len,char*str,int top)
{
    stackk[top++]=str[s];
    if(top==len)
    {
        visit[str[s]]=0;
        cout<<stackk<<endl;
        return;
    }
    visit[str[s]]=1;
    for(int i=0;i<len;++i)
    {
        if(visit[str[i]]==0)
        {
            visit[str[i]]=1;
            DFS(i,len,str,top);
        }
    }
    visit[str[s]]=0;//重置访问标记位
}
void DFSPermut(char *str)
{
    int len=strlen(str);
    int top=0;
    for(int i=0;i<len;++i)
    {
        for(int j=0;j<len;++j)
        {
            visit[str[j]]=0;
        }
        DFS(i,len,str,top);
    }
}


包含重复元素的排列:按照思路1,如果当前第i个字符,存在于[start,i)说明,前面已经等价交换过一次,故不用交换。

void permutation(char*str,char*start)
{
    if(*(start+1)=='\0')
    {
        cout<<str<<endl;
    }
    else
    {
        for(char*p=start;*p!='\0';++p)
        {
            if(IsSwap(start,p,*p)==false)continue;
            cswap(p,start);
            permutation(str,start+1);
            cswap(p,start);
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值