首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >打印C语言中字符串的所有排列

打印C语言中字符串的所有排列
EN

Stack Overflow用户
提问于 2013-06-08 01:22:02
回答 5查看 49.5K关注 0票数 18

我正在学习回溯和递归,并且我被一种打印字符串的所有排列的算法所困扰。我用置换的bell algorithm解决了这个问题,但是我不能理解递归方法。我在网上搜索了一下,发现了下面的代码:

代码语言:javascript
复制
void permute(char *a, int i, int n) 
{
   int j; 
   if (i == n)
     printf("%s\n", a);
   else
   {
        for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j)); 
       }
   }
} 

我不明白这个算法是怎么工作的?我甚至尝试过干式跑步!

回溯是如何应用的?

在计算排列时,它是否比Bell算法更有效?

EN

回答 5

Stack Overflow用户

发布于 2014-02-18 18:21:47

递归确实简化了它:

代码语言:javascript
复制
public static void permutation(String str) 
{ 
    permutation("", str); 
}

private static void permutation(String prefix, String str) 
{
    int n = str.length();
    if (n == 0) {
        System.out.println(prefix);
    } else {
        for (int i = 0; i < n; i++)
            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
    }
}
票数 5
EN

Stack Overflow用户

发布于 2014-05-22 11:07:21

伪代码:

代码语言:javascript
复制
String permute(String a[])
{
  if (a[].length == 1)
     return a[];
  for (i = 0, i < a[].length(); i++)
    append(a[i], permute(a[].remove(i)));
}
票数 1
EN

Stack Overflow用户

发布于 2014-10-10 03:21:23

代码语言:javascript
复制
I create more specific but not efficient Program for permutation for general string.
It's work nice way.
//ubuntu 13.10 and g++ compiler but it's works on any platform and OS
//All Permutation of general string.

#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
using namespace std;
int len;
string str;

void permutation(int cnum)
{
    int mid;
    int flag=1;
    int giga=0;
    int dead=0;
    int array[50];
    for(int i=0;i<len-1;i++)
    {
        array[50]='\0';
        dead=0;
        for(int j=cnum;j<len+cnum;j++)
        {
            mid=j%len;
            if(mid==cnum && flag==1)
            {
                cout<<str[mid];
                array[dead]=mid;
                dead++;
                flag=0;
            }
                else
            {
                giga=(i+j)%len;
                for(int k=0;k<dead;k++)                 
                {
                    if((array[k]==giga) && flag==0)
                    {
                    giga=(giga+1)%len;
                    }
                }
                cout<<str[giga];
                array[dead]=giga;
                dead++;

            }
        }
        cout<<endl;
        flag=1; 
    }
}
int main()
{
    cout<<"Enter the string :: ";
    getline(cin,str);
    len=str.length();
    cout<<"String length = "<<len<<endl;
    cout<<"Total permutation = "<<len*(len-1)<<endl;
    for(int j=0;j<len;j++)
    {
        permutation(j);
    }
return 0;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16989689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档