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>

  1. tia on 2014-3-2

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

    }

    }

    }

    }

  2. ryanlr on 2014-3-3

    Can you put your code inside you code ? Thanks.

  3. junmin on 2014-4-6
  4. Jason on 2014-6-4

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

  5. zhou2214 on 2014-9-13

    Integer a=0;

  6. Panda on 2014-9-19

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

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

  7. Nathan Glenn on 2014-12-29

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

  8. rakesh singh on 2015-9-21

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

  9. Kamal Chaya on 2015-10-24

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

  10. CRH on 2015-12-8

    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;

  11. Simon on 2016-2-20

    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.

  12. hh on 2016-3-14

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

  13. Pratik Upacharya on 2016-6-29

    Test case :

    5 elements in set .
    2 2 2 2 2

    It should return 1 , instead of 120 .

Leave a comment

*