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]
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 |
public class Solution { public
ArrayList<ArrayList<Integer>> permute( int [] num) { ArrayList<ArrayList<Integer> > result = new
ArrayList<ArrayList<Integer> >(); if (num.length > 0 ){ ArrayList<Integer> list = new
ArrayList<Integer>(); list.add(num[ 0 ]); result.add(list); int
length = 1 ; for ( int
i = 1 ; i < num.length; ++i){ length *= i; for ( int
j = 0 ; j < length; ++j){ ArrayList<Integer> newList = result.remove( 0 ); for ( int
k = 0 ; k < i + 1 ; ++k){ ArrayList<Integer> addedList = new
ArrayList<Integer>(); addedList.addAll(newList); addedList.add(k, num[i]); result.add(addedList); } } } } return
result; } } |
原文:http://www.cnblogs.com/averillzheng/p/3542226.html