[LeetCode] 46. Permutations

Problem

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

Example:

1
2
3
4
5
6
7
8
9
10
Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

Explanation

  1. From the above example, for the first element in the sublist, we can choose $1$, $2$, or $3$, for the second number, we can still choose $1$, $2$, or $3$ but with the condition that the number we are going to add must not appear before. So, we need a for loop to iterate the number, and we need a visited array to keep track of the visited number.

  2. Base case is whenever the sublist’s length is equal to the nums length, then we return.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
    void dfs(int[] nums, List<Integer> temp, List<List<Integer>> res, boolean[] visited) {
        if (temp.size() == nums.length) {
            res.add(new ArrayList<Integer>(temp));
            return;
        }
        
        for (int i = 0; i < nums.length; i++) {
            if (visited[i] == false) {
                temp.add(nums[i]);
                visited[i] = true;
                dfs(nums, temp, res, visited);
                temp.remove(temp.size()-1);
                visited[i] = false;
            }
        }
    }
    
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<>();
        boolean[] visited = new boolean[nums.length];
        dfs(nums, temp, res, visited);
        return res;
    }
}