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.
Since C(n)=1+C(n-1), if we expand it, we can get time complexity is O(N!).
<pre><code> String foo = "bar"; </code></pre>
-
alexwest11
-
alexwest11
-
Pratik Upacharya
-
hh
-
Simon
-
CRH
-
Kamal Chaya
-
rakesh singh
-
Nathan Glenn
-
Panda
-
zhou2214
-
Jason
-
junmin
-
ryanlr
-
tia