Permutations
Problem
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
helper(res, new ArrayList<>(), nums);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> list, int[] nums) {
if(list.size() == nums.length) {
res.add(new ArrayList<>(list));
return ;
}
for(int i = 0; i < nums.length; i++) {
if(list.contains(nums[i])) continue;
list.add(nums[i]);
helper(res, list, nums);
list.remove(list.size() - 1);
}
}
}
Analysis
A typical backtracking solution
Notice that we don't have int start as a parameter in helper() method
This is because there is no order required in permutations
If start reaches end, there is no way to add other element from nums
Hence we use regular for loop from 0 to end