leetcode -- Permutations
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 public class Solution { 2 public ArrayList<ArrayList<Integer>> permute(int[] num) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int len = num.length; 6 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 7 permutation(num, 0, len, result); 8 return result; 9 } 10 11 public void permutation(int[] num, int depth, int len, ArrayList<ArrayList<Integer>> result){ 12 if(depth == len){ 13 ArrayList<Integer> per = new ArrayList<Integer>(); 14 for(int i =0 ; i < len; i++) 15 per.add(num[i]); 16 17 result.add(per); 18 } 19 20 for(int i = depth; i < len; i++) { 21 int tmp = num[i]; 22 num[i] = num[depth]; 23 num[depth] = tmp; 24 25 permutation(num, depth + 1, len, result); 26 27 tmp = num[i]; 28 num[i] = num[depth]; 29 num[depth] = tmp; 30 } 31 } 32 }