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]
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.combinations; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
/** | |
* Problem: How to make it as Permutation according to combination? | |
* -- don't use position as start marker. Help only has three parameters. | |
* | |
* Every time we can get other element from whole int[],start from 0, so i=0, just need to remove duplicate | |
* | |
* if list.size() == num.length, we add a result and return, Actually, remove return; will not have influence on final result. | |
* the program will slow because it will enter following loop until go out. | |
* (Every time it contains, and continue because of full of different elements stored already) | |
* | |
* In addition, we remove Arrays.sort(num) because permutation don't care non-descending order. | |
* | |
* @author jeffwan | |
* @date Feb 10, 2014 | |
*/ | |
public class Permutations { | |
public ArrayList<ArrayList<Integer>> permute(int[] num) { | |
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); | |
ArrayList<Integer> list = new ArrayList<Integer>(); | |
permuteHelper(result, list, num); | |
return result; | |
} | |
private void permuteHelper(ArrayList<ArrayList<Integer>> result, | |
ArrayList<Integer> list, int[] num) { | |
if (list.size() == num.length) { | |
result.add(new ArrayList<Integer>(list)); | |
return; | |
} | |
for (int i = 0; i < num.length; i++) { | |
if (list.contains(num[i])) { | |
continue; | |
} | |
list.add(num[i]); | |
permuteHelper(result, list, num); | |
list.remove(list.size() - 1); | |
} | |
} | |
} |
No comments:
Post a Comment