46 Permutations

1. Question

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

For example, [1,2,3]have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

2. Implementation

(1) Backtracking

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> permutation = new ArrayList<>();
        boolean[] used = new boolean[nums.length];
        getPermutations(nums, used, permutation, res);
        return res;
    }

    public void getPermutations(int[] nums, boolean[] used, List<Integer> permutation, List<List<Integer>> res) {
        if (permutation.size() == nums.length) {
            res.add(new ArrayList<>(permutation));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (!used[i]) {
                used[i] = true;
                permutation.add(nums[i]);
                getPermutations(nums, used, permutation, res);
                permutation.remove(permutation.size() - 1);
                used[i] = false;
            }
        }
    }
}

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!), 空间复杂度O(n!)

Last updated