C 是否将字符串的所有可能排列存储在数组中?
我想在字符串数组中存储字符串的所有排列 现在我使用的代码是:C 是否将字符串的所有可能排列存储在数组中?,c,permutation,C,Permutation,我想在字符串数组中存储字符串的所有排列 现在我使用的代码是: # 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) {
# 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;
}
您正在为所有元素在pms数组中存储相同的地址,即a的地址。您应该创建内存来保存这些组合,并复制每个组合数组而不是赋值。了解数组和指针之间的区别。另外,请阅读如何填充数组a,特别是如何填充以C字符串零结尾的字符数组。请参阅本页上的str*-函数族。