↻one more pass.
Backtracking · Medium

Permutations: the idea to remember.

Return all orderings of an array of distinct integers.

Solve on LeetCode ↗

The core insight

Choose one unused value for each position, restore its availability after recursion, and copy completed paths.

Why it works

Every ordering chooses a distinct remaining value at each depth, covering all permutations exactly once.

The mistake to avoid

Restore the used marker or swapped values before exploring the next branch.

Time: O(n · n!) including outputSpace: O(n) auxiliary plus output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Choose one unused value for each position, restore its availability after recursion, and copy completed paths.
public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> ans = new ArrayList<>();
    function(ans, nums, 0);
    return ans;
}

public void function(List<List<Integer>> ans, int[] arr, int start) {
    if (start == arr.length) {
        List<Integer> list = new ArrayList();
        for (int i = 0; i < arr.length; i++) list.add(arr[i]);
        ans.add(list);
        return;
    }

    for (int i = start; i < arr.length; i++) {
        swap(arr, start, i);
        function(ans, arr, start + 1);
        swap(arr, start, i);
    }
}

public void swap(int[] arr, int a, int b) {
    int temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.