Wednesday, October 20, 2021

Permutation Generate using Backtracking

Permutation means an arrangement of some elements into a sequence of order. Suppose an array A[] = {1,2,3}, its all possible permutation is, 
{ [1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1] }, Permutation calculate by N! ( N factorial). N is the size of an array.

So here N is 3, so 3! means 6 possible permutations can be generated.

Before Solving permutation, we know how subsets can be generated. In subsets calculations, Every size of subsets can be different, right?

But, Here in permutation every size of its arrangement is the same as the given array size, right ?
So, what's happening here, we just changing their position, isn't it?

See, {1,2,3}, {1,3,2}. We just change their position 2 to 3 , 3 to 2.

So, we don't need the extra array to calculate every arrangement of permutation, but in subsets calculation, we have used an extra array so that we can store all possible subsets because of their different sizes.

That means, here permutation calculation we can just swap their position.

So, our state is position, and base case is if position reach at the end of the array then simply we can add this arrangement to our answer.

But we need to do a simple operation, just run a loop from the current position and swap every element with the current position and again call another recursive with position+1.
At the same time after calling another recursive function, we need to re-swap their position, here backtracking happening.

Simple code: 
vector<vector<int>>ans;
void per(int pos, vector<int>&a){
        if(pos == a.size()-1){
            ans.push_back(a);
            return;
        }
       for(int i = pos; i<a.size(); i++){
           swap(a[i], a[pos]); // changing their position
           per(pos+1, a);
           swap(a[i], a[pos]); // backtracking
       }
}


You can submit your solution here.



No comments:

Post a Comment