我想将字符串的所有排列存储在字符串数组中...
现在我正在使用的代码是:
# include <stdio.h>
char *pms[] = {};
int pmsi = 0;
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n) {
pms[pmsi] = a;
pmsi++;
}
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
/* Driver program to test above functions */
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
int i;
for (i = 0 ; i < pmsi ; i++) {
printf("%s",pms[i]);
}
return 0;
}
但是崩溃了...
我不想打印出所有可能的排列……我想将它们存储在数组中。
是否解决?
我能够解决这个问题。
# include <stdio.h>
char *pms[];
int pmsi = 0;
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n) {
pms[pmsi] = a;
pmsi++;
}
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
/* Driver program to test above functions */
int main()
{
char a[] = "ABC";
permute(a, 0, 2);
int i;
for (i = 0 ; i < pmsi ; i++) {
printf("%s",pms[i]);
}
return 0;
}
此作品
但是现在不打印排列。原始字符串被打印。任何帮助???
此代码对于上述动机非常有效:-
#include<bits/stdc++.h>
using namespace std;
vector<string> pms;
void permute(string a, int l, int r)
{
if (l == r) {
pms.push_back(a);
}
else
{
for (int j = l; j <= r; j++)
{
swap(a[l],a[j] );
permute(a, l+1, r);
swap(a[l], a[j]);
}
}
}
int main()
{
string a = "ABC";
permute(a, 0, 2);
int i;
for (i = 0 ; i < pms.size() ; i++) {
cout<<pms[i]<<"\n";
}
return 0;
}