Find all Permutations of given array | Cpp solution, Backtracking

 Statement-

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

 

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

code - 
class Solution {
    vector<vector<int>> ans;
    
    void perm(vector<int> &v, int s, int e)
    {
        if(s == e)
        {
            ans.push_back(v);
        }
        else
        {
            for(int i = s; i <= e; i++)
            {
                swap(v[i], v[s]);
                perm(v, s+1, e);
                
                swap(v[i], v[s]);
            }
        }
    }
public:
    vector<vector<int>> permute(vector<int>& nums) {
        int n = nums.size();
        
       perm(nums, 0, n-1);
        
        return ans;
    }
};
Reactions

Post a Comment

0 Comments