Given a collection of distinct integers, return all possible permutations.
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length == 0)
return res;
List<Integer> line = new ArrayList<>();
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
helper(res, line, nums, visited);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> line, int[] nums, boolean[] visited) {
if(line.size() == nums.length) {
res.add(new ArrayList<>(line));
return;
}
for(int i = 0; i < nums.length; i++) {
if(visited[i])
continue;
line.add(nums[i]);
visited[i] = true;
helper(res, line, nums, visited);
visited[i] = false;
line.remove(line.size() - 1);
}
}
}