Backtracking

Permutations

Estimated reading: 1 minute 29 views

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

Example 1:

Input: nums = [1,2,3]

Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
				
					 public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();

        if (nums.length == 1) {
            List<Integer> singleNum = new ArrayList<>();
            singleNum.add(nums[0]);
            res.add(singleNum);
            return res;
        }

        for (int i = 0; i < nums.length; i++) {
            int n = nums[i];
            int[] remainingNums = new int[nums.length - 1];
            int idx = 0;
            for (int j = 0; j < nums.length; j++) {
                if (j != i) {
                    remainingNums[idx++] = nums[j];
                }
            }
            List<List<Integer>> perms = permute(remainingNums);

            for (List<Integer> perm : perms) {
                perm.add(n);
                res.add(new ArrayList<>(perm));
            }
        }
        return res;
    }
				
			
Share this Doc

Permutations

Or copy link

CONTENTS