151 DSA Problem journey

151 DSA Problem journey

Permutations

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

Example :

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Solution:
class Solution {
public:
vector<vector<int>>ans;
void helper(vector<int>&nums,int i){
    if(i==nums.size()){
        ans.push_back(nums);
        return;
    }
    for(int j=i;j<nums.size();j++){
        swap(nums[i],nums[j]);
        helper(nums,i+1);
        swap(nums[i],nums[j]);
    }
    return;
}
    vector<vector<int>> permute(vector<int>& nums) {
        helper(nums,0);
        return ans;      
    }
};
Explantion:
>Permute function returns all possible permutations of the given vector nums.
>It initializes an empty 2D vector ans to store the permutations.
>Helper function is a recursive function that generates permutations.
>If the index i reaches the size of nums, it adds the current permutation to ans and returns.
>It iterates through the vector starting from index i.
>Swaps elements at indices i and j to create permutations.
>Recursively calls helper with the updated vector and index.
>After the recursive call, swaps back elements to backtrack and explore other permutations.
>The final result is stored in the 2D vector ans.

#If anyone have better solution so please comment:)