具有重复字符的字符串的排列(访问数组概念)

时间:2016-10-23 16:29:01

标签: c++ string math permutation

void per(int count){

    if(count==l){
       printf("%s\n", p);
       return;
    }

    for(int i=0;i<l;i++){
          if(visit[i]==0 ){
          visit[i]=1;
          p[count]=arr[i];
          per(count+1);
          visit[i]=0;   //backtrack
          }
    }
}

上面提到的代码是为字符串“aab”生成的,以下是排列。

aab
aba
aab
aba
baa
baa

重复一些置换字符串?我怎样才能减少它? 链接到我的code

1 个答案:

答案 0 :(得分:1)

您使用的是C ++,因此std:next_permutation是您最好的朋友。

如果您想从头开始实现排列,请使用algorithm description for the next lexicographic permutation。请注意,算法适用于重复元素。

Find the largest index k such that a[k] < a[k + 1]. If no such index exists, 
   the permutation is the last permutation.

Find the largest index l greater than k such that a[k] < a[l].

Swap the value of a[k] with that of a[l].

Reverse the sequence from a[k + 1] up to and including the final element a[n].

任意c ++ implementation