两种思路 一种是从第一个数开始add 之后每个数add就是在上一条n个数中选一个位置insert 共n+1种
这种就是浪费了一些小的list 因为下面要复制sublist
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); helper ( res, nums, new ArrayList<Integer>(), 0 ); return res; } public void helper ( List<List<Integer>> res, int [] nums, List<Integer> temp, int k ){ if ( k >= nums.length ){ res.add ( temp ); return; } for ( int i = 0; i <= temp.size(); i ++ ){ List<Integer> next = new ArrayList<Integer>(temp); ////这里 next.add ( i, nums [ k ] ); helper ( res, nums, next, k + 1 ); } } }
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); helper ( res, nums, 0 ); return res; } public void helper ( List<List<Integer>> res, int [] nums, int k ){ if ( k >= nums.length ){ List<Integer> temp = new ArrayList<Integer> (); for ( int i = 0; i < nums.length; i ++ ) temp.add ( nums [ i ] ); res.add ( temp ); return; } for ( int i = k; i < nums.length; i ++ ){ swap ( nums, i , k ); helper ( res, nums, k + 1 ); swap ( nums, i , k ); } } public void swap ( int [] nums, int i, int j ) { int temp = nums [ i ]; nums [ i ] = nums [ j ]; nums [ j ] = temp; } }