L46. Permutations

Problem:

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Solution:

public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    if(nums == null || nums.length == 0) return ans;
    List<Integer> list = new ArrayList<>();
    dfs(ans, list, nums);
    return ans;
}
private void dfs(List<List<Integer>> ans, List<Integer> list, int[] nums){
    if(list.size() == nums.length){
        ans.add(new ArrayList<>(list));
        return;
    }
    for(int i = 0; i < nums.length; i++){
        if(list.contains(nums[i])) continue;
        list.add(nums[i]);
        dfs(ans, list, nums);
        list.remove(list.size() - 1);            
    }            
}

Last updated

Was this helpful?