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]
.
public class Solution { /** * dynamic programming method. * the permutation contains num[0] is one. * For num[1], there are two place to insert it and get two lists <num[1], num[0]>, <num[0], num[1]>. Using * this idea, if we have insert num[i - 1] and get their permutaton, now we insert num[i] into each list. * There are (i + 1) position (=length of list + 1) to place num[i]. * @param num --Integer array. * @return List<List<Integer>> --the collection of all permutation of num. * @author Averill Zheng * @version 2014-06-05 * @since JDK 1.7 */ public List<List<Integer>> permute(int[] num) { List<List<Integer> > result = new ArrayList<List<Integer>>(); int length = num.length; if(length > 0){ List<Integer> startList = new ArrayList<Integer>(); startList.add(num[0]); result.add(startList); int size = 1; for(int i = 1; i < length; ++i){ List<List<Integer>> tempResult = new ArrayList<List<Integer> >(); for(int j = 0; j < size; ++j){ List<Integer> aList = result.get(j); for(int k = 0; k < i + 1; ++k){ List<Integer> newList = new ArrayList<Integer>(); newList.addAll(aList); newList.add(k, num[i]); tempResult.add(newList); } } size *= (i + 1); result = tempResult; } } return result; } }