Permutations Leetcode Solution in java | Hindi Coding Community

0

 


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



class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
helper(nums,0,ans);
return ans;
}
public void helper(int[] nums, int index, List<List<Integer>> ans)
{
if(index==nums.length){
ArrayList<Integer> list =new ArrayList<>();
for(int i = 0 ; i<nums.length ; i++){
list.add(nums[i]);
}
ans.add(list);
return;
}
for(int i = index; i<nums.length; i++){
swap(i,index,nums);
helper(nums, index+1, ans);
swap(i,index,nums);
}
}
public static void swap(int i , int j, int[] nums){
int t=nums[i];
nums[i]=nums[j];
nums[j]=t;
}
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !