String Permutation in C++
String Permutation in C++
#include<iostream>
#include<conio.h>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
void calculatePermutation(const string &str,string &res,vector<int> &count,vector<string> &result,int level,int maxLevel){
if (level == maxLevel){
result.push_back(res);
return;
}
for (int i = 0; i < str.length(); i++){
if (count[i] > 0){
res[level] = str[i];
count[i] = count[i] - 1;
calculatePermutation(str, res, count, result, level + 1, maxLevel);
count[i] = count[i] + 1;
}
}
}
void permutation(const string &input,vector<string> &result,int r){
int i,val;
char ch;
string temp = input;
sort(temp.begin(),temp.end());
vector<int> count;
string temp2="";
i = 0;
while (i < input.length()){
ch = temp[i];
val = 0;
while (ch == temp[i]){
val++;
i++;
}
temp2.push_back(ch);
if (val > r)
val = r;
count.push_back(val);
}
string res (r, ' ');
calculatePermutation(temp2,res,count,result,0,r);
}
int main(){
string input = "aaaabbbbbaaaaaabbbbbbbb";
vector<string> res;
permutation(input, res, 3);
for (int i = 0; i < res.size(); i++)
cout << res[i] << endl;
_getch();
return 0;
}
Comments
Post a Comment