【发布时间】:2016-06-09 16:10:12
【问题描述】:
我有两种打印字符串排列的算法
这是第一个。
#include<iostream>
int fact(int f)
{
if(f == 0)
return 1;
return f*fact(f-1);
}
int main()
{
char A[] = "abc";
int size = strlen(A);
int per = fact(size); // per is the number of permutations we will get
int j = 0; // j is the index of the elements of A we will swap
// this is the algorithm
for(int i=1;i<=per;i++)
{
cout << A << endl;
if(j == size-1)
j = 0;
swap(A[j],A[j+1]);
j++;
}
return 0;
}
这是第二个。
// C program to print all permutations of the input string
#include <stdio.h>
#include <string.h>
// Function to swap values at two pointers
void swap(char *x, char *y)
{
char 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 or sub-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 to retain the original string
}
}
}
int main()
{
char str[50];
gets_s(str);
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
据我说...两者都应该执行相同的操作...实际上它们确实可以...但仅适用于小输入...例如:“abc”,“abcd”。但是当字符串变大时..例如: "abcdefghi"..第一个比第二个要花很多时间。
我很难分析为什么第二个比第一个表现更好。有人可以向我解释一下吗?
【问题讨论】:
-
我认为事实函数是罪魁祸首。您是否尝试计算大于 10 的数的阶乘? 15? 20?
-
让你的事实函数使用循环而不是递归并再次检查。如果它更快,那就是你的问题。
-
您使用哪种语言?请比较喜欢和喜欢。
-
我使用 c 和 c++
-
我不认为事实是一个问题,因为我首先计算阶乘....然后才开始打印...如果您尝试运行打印将花费很多时间代码
标签: c++ string algorithm permutation