Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
OR
Given a collection of numbers, return all possible permutations.
NOTE: No two entries in the permutation sequence should be the same. For the purpose of this problem, assume that all the numbers in the collection are unique.
Warning : DO NOT USE LIBRARY FUNCTION FOR GENERATING PERMUTATIONS. Example : next_permutations in C++ / itertools.permutations in python. If you do, we will disqualify your submission retroactively and give you penalty points.
A list to represent permutation constructed so far, path
A list to record which letters are already used, used, visited[i] == true means ith letter in the origin list has been used.
public List<List<Integer>>permute(int[] nums) {
boolean[] visited =newboolean[nums.length];
List<List<Integer>> ans =new ArrayList<>();
helper(nums,visited,ans, new ArrayList<>());
return ans;
}
voidhelper(int[] nums, boolean[] visited, List<List<Integer>> ans, List<Integer> subAns) {
if (subAns.size() == nums.length){
ans.add(new ArrayList<>(subAns));
return;
}
for(int i=0;i<nums.length;i++){
if(visited[i]) {
continue;
}
subAns.add(nums[i]);
visited[i]=true;
helper(nums,visited,ans,subAns);
visited[i]=false;
subAns.remove(subAns.size()-1);
}
}
Note: It is very important to do:
1
ans.add(new ArrayList<>(subAns));
and not:
1
ans.add(subAns);
As, subAns is constantly modified. So, they will be become empty[] eventually, so we will get wrong answer. new ArrayList<>(subAns) creates deep copy.
Method 2 - Backtracking with Swapping Elements in Array#
We can follow following steps:
Step 0: Initialize the variables start and end with start = 0 and end = n - 1. Call the method: permutations(array, start, end).
Step 1: Loop over the array from start to end using an index.
Step 2: Fix the character at the current index by swapping the character at start with the character at the index.
Step 3: Recursively generate all permutations for the remaining positions by calling the method again with updated parameters: permutations(array, start + 1, end).
Step 4: Backtrack by swapping the character at start back with the character at the index.