LeetCode – Permutations (Java)

Given a collection of 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], and [3,2,1].

Java Solution 1 – Iteration

We can get all permutations by the following steps:

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

Loop through the array, in each iteration, a new number is added to different locations of results of previous iteration. Start from an empty List.

public ArrayList<ArrayList<Integer>> permute(int[] num) {
	ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 
	//start from an empty list
	result.add(new ArrayList<Integer>());
 
	for (int i = 0; i < num.length; i++) {
		//list of list in current iteration of the array num
		ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
 
		for (ArrayList<Integer> l : result) {
			// # of locations to insert is largest index + 1
			for (int j = 0; j < l.size()+1; j++) {
				// + add num[i] to different locations
				l.add(j, num[i]);
 
				ArrayList<Integer> temp = new ArrayList<Integer>(l);
				current.add(temp);
 
				//System.out.println(temp);
 
				// - remove num[i] add
				l.remove(j);
			}
		}
 
		result = new ArrayList<ArrayList<Integer>>(current);
	}
 
	return result;
}

Java Solution 2 – Recursion

We can also recursively solve this problem. Swap each element with each element after it.

public List<List<Integer>> permute(int[] nums) {
    List<List<Integer>> result = new ArrayList<>();
    helper(0, nums, result);
    return result;
}
 
private void helper(int start, int[] nums, List<List<Integer>> result){
    if(start==nums.length-1){
        ArrayList<Integer> list = new ArrayList<>();
        for(int num: nums){
            list.add(num);
        }
        result.add(list);
        return;
    }
 
    for(int i=start; i<nums.length; i++){
        swap(nums, i, start);
        helper(start+1, nums, result);
        swap(nums, i, start);
    }
}
 
private void swap(int[] nums, int i, int j){
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

Here is a manual execution of this program. Each depth is from left to right.
leetcode permutations java

Since C(n)=1+C(n-1), if we expand it, we can get time complexity is O(N!).

15 thoughts on “LeetCode – Permutations (Java)”

  1. #recursively solve this problem

    number calls of ‘ helper’ is bigger than n!. what is the point?

  2. l.add/ l.remove in 1st example is very bad!!

    better, add num[i] element to end of L (current arraylist)
    and then just exchange w/ prev, each time new arraylist

    12, num[i] =3

    123
    132
    312

  3. public class Solution {

    public ArrayList<arraylist> permute(int[] num) {

    ArrayList<arraylist> result = new ArrayList<arraylist>();

    if(num == null || num.length<0) return result;

    int len = num.length;

    ArrayList visited = new ArrayList();

    dfsList(len, num, visited, result);

    return result;

    }

    public void dfsList(int len, int[] num, ArrayList visited, ArrayList<arraylist> result){

    if(visited.size() == len){

    result.add(new ArrayList(visited));

    return;

    }

    for(int i=0; i<len; i++){="" if(!visited.contains(num[i])){="" visited.add(num[i]);="" dfslist(len,="" num,="" visited,="" result);="" visited.remove(visited.size()-1);="" }="" }="" }="" }=""

  4. This order of the permutations from this code is not exactly correct. The test case: (1,2,3) adds the sequence (3,2,1) before (3,1,2). The exact solution should have the reverse. It will still pass the Leetcode test cases as they do not check for ordering, but it is not a lexicographical order.

  5. In the swap function of recursive solution we should add a minor optimization. Modified swap function should start with one extra line.


    if (i==j) return;

  6. The variable “l” is an object inside of the list “result”. If you do not copy “l”, then the final list will contain multiple entries that are the same object, or the entry could have an entry removed (“l.remove(j)”).

  7. 你好,我想请问一下 solution1 里面为什么 要加ArrayList temp = new ArrayList(l) 这么一行, 直接 current.add(l) 不行么?

  8. I have another solution using dfs:

    public class Solution {

    public ArrayList<ArrayList> permute(int[] num) {

    ArrayList<ArrayList> result = new ArrayList<ArrayList>();

    if(num == null || num.length<0) return result;

    int len = num.length;

    ArrayList visited = new ArrayList();

    dfsList(len, num, visited, result);

    return result;

    }

    public void dfsList(int len, int[] num, ArrayList visited, ArrayList<ArrayList> result){

    if(visited.size() == len){

    result.add(new ArrayList(visited));

    return;

    }

    for(int i=0; i<len; i++){

    if(!visited.contains(num[i])){

    visited.add(num[i]);

    dfsList(len, num, visited, result);

    visited.remove(visited.size()-1);

    }

    }

    }

    }

Leave a Comment