0046 - Permutations

0046 - Permutations

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Examples

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

Input: nums = [0,1] Output: [[0,1],[1,0]]

Input: nums = [1] Output: [[1]]

Constraints:

1 <= nums.length <= 6 -10 <= nums[i] <= 10 All the integers of nums are unique.

Java Solution (Backtracking)

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> perms = new ArrayList<>();
        permuteHelper(perms, new ArrayList<>(), nums);
        return perms;
    }
    
    private void permuteHelper(List<List<Integer>> perms, List<Integer> tempList, int[] nums) {
        if(tempList.size() == nums.length){
            perms.add(new ArrayList<>(tempList));
        } else{
            for(int i = 0; i < nums.length; i++) {
                if(tempList.contains(nums[i])) continue; // element already exists, skip
                 tempList.add(nums[i]);
                 permuteHelper(perms, tempList, nums);
                 tempList.remove(tempList.size() - 1);
            }
        }
    }
}

Last updated