Permutation of Array Problem

 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]]

Example 2:


Input: nums = [0,1]

Output: [[0,1],[1,0]]

Example 3:


Input: nums = [1]

Output: [[1]]


class Solution {
    public List<List<Integer>> permute(int[] nums) {
        int start=0;
        List<List<Integer>> result=new ArrayList<>();
     generatePermutation(nums, start, result); // Call the function (no return here)
        return result; // Now return the result
    }
    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j]=temp;
     
    }
    public static void generatePermutation(int []nums,int start,List<List<Integer>> result)
    {
        if(start==nums.length) // base case
        {
List<Integer> per=new ArrayList<>();

for(int i:nums)
{
    per.add(i);
}
  result.add(per);
        return;
        }

        for(int i=start;i<nums.length;i++)
        {
            swap(nums,i,start);
            generatePermutation(nums,start+1,result);
            swap(nums,i,start);

        }

     
    }




}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence