2016-10-22 35 views
0

置换也称为“排列编号”或“顺序”,是将有序列表S的元素重新排列为与S本身一一对应。长度为n的字符串有n!排列。 下面是字符串ABC的排列。 ABC ACB BAC BCA CBA CAB任何人都可以为我的代码建议我进行必要的更改吗?

以下所有可能的字符串排列代码使用回溯编码,但它不起作用,任何人都请提出必要的更改。

C程序来打印所有排列与允许重复 -

#include <stdio.h> 
#include <string.h> 

/* Function to swap values at two pointers */ 
void swap(char *x, char *y) 
{ 
    char temp; 
    temp = *x; 
    *x = *y; 
    *y = temp; 
} 

    /* Function to print permutations of string 
    This function takes three parameters: 
    1. String 
    2. Starting index of the string 
    3. Ending index of the string. */ 
void permute(char *a, int l, int r) 
{ 
    int i; 
    if (l == r) 
    printf("%s\n", a); 
    else 
    { 
     for (i = l; i <= r; i++) 
     { 
     swap((a+l), (a+i)); 
     permute(a, l+1, r); 
     swap((a+l), (a+i)); //backtrack 
     } 
    } 
} 

/* Driver program to test above functions */ 
int main() 
{ 
    char str[] = "ABC"; 
    int n = strlen(str); 
    permute(str, 0, n); 
    return 0; 
    } 
+0

你能解释一下哪些工作不正常,或者你目前的结果是什么? – Isuka

回答

1

这是OBOB的典型例子(由一个错误)。

n长度字符串的最后一个字符的索引是n-1,因此当循环查找字符串中的所有索引时,循环不应该是for (i = l; i <= r; i++),而是for (i = l; i < r; i++)

使用太大的索引调用swap()会创建奇怪的效果,例如缩短字符串的长度。

这是变更后的置换()函数:

void permute(char *a, int l, int r) 
{ 
    int i; 
    if (l == r) 
    printf("%s\n", a); 
    else 
    { 
     for (i = l; i < r; i++) // corrected indices 
     { 
     swap((a+l), (a+i)); 
     permute(a, l+1, r); 
     swap((a+l), (a+i)); //backtrack 
     } 
    } 
} 

现在应该工作。

相关问题