C++- Simple Backtracking brute force solution


#1
// Brute force solution!
string mx="";
void find(string a,int k){
    if(k==0){
        if(mx<a) mx=a;
        return;
    }
    for(int i=0;i<a.length();i++){
        for(int j=i+1;j<a.length();j++){
            swap(a[i],a[j]);
            find(a,k-1);
            swap(a[i],a[j]);
        }
    }
}
string Solution::solve(string A, int B) {
    mx="";
    find(A,B);
    return mx;
}

#2

Wrong answer for
987 and k = 1


#3

mx should be initialized to A.

string mx="";
void find(string a,int k){
if(k==0){
if(mx<a) mx=a;
return;
}
for(int i=0;i<a.length();i++){
for(int j=i+1;j<a.length();j++){
swap(a[i],a[j]);
find(a,k-1);
swap(a[i],a[j]);
}
}
}
string Solution::solve(string A, int B) {
mx=A;
find(A,B);
return mx;
}