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

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

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

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

Here is a manual execution of this program.
leetcode permutations java

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Pratik Upacharya

    Test case :

    5 elements in set .
    2 2 2 2 2

    It should return 1 , instead of 120 .

  • hh

    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);="" }="" }="" }="" }=""

  • Simon

    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.

  • CRH

    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;

  • Kamal Chaya

    Would they ever ask you to do it without recursion in an interview? :/

  • rakesh singh

    well explain and you can refer this link also
    string permutation in easy way

  • Nathan Glenn

    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)”).

  • Panda

    the element will be removed if we do not do a copy of the lsit

    // – remove num[i] add
    l.remove(j);

  • zhou2214

    Integer a=0;

  • Jason

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

  • junmin
  • ryanlr

    Can you put your code inside you code ? Thanks.

  • tia

    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);

    }

    }

    }

    }