LintCode——全排列
描述:给定一个数字列表,返回其所有可能的排列。
样例:给出一个列表[1,2,3]
,其全排列为:[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
说明:分别使用递归和非递归实现
Java
1、递归
1 public class Solution { 2 /* 3 * @param nums: A list of integers. 4 * @return: A list of permutations. 5 */ 6 public List<List<Integer>> permute(int[] nums) { 7 List<List<Integer>> res = new ArrayList<>(); 8 if(nums == null) 9 return res; 10 if(nums.length == 0) 11 { 12 res.add(new ArrayList<Integer>()); 13 return res; 14 } 15 16 ArrayList<Integer> list = new ArrayList<>(); 17 dfs(res, list, nums); 18 return res; 19 } 20 21 private void dfs(List<List<Integer>> res, ArrayList<Integer> list, int[] nums) {//深度优先 22 23 int n = nums.length; 24 if(list.size() == n) 25 { 26 res.add(new ArrayList<Integer>(list)); 27 return; 28 } 29 30 for(int i = 0;i < n;i++) { 31 if(list.contains(nums[i])) 32 continue; 33 list.add(nums[i]); 34 dfs(res, list, nums); 35 list.remove(list.size() - 1); 36 } 37 } 38 }
2、非递归
1 public class Solution { 2 /* 3 * @param nums: A list of integers. 4 * @return: A list of permutations. 5 */ 6 public List<List<Integer>> permute(int[] nums) { 7 List<List<Integer>> res = new ArrayList<List<Integer>>(); 8 if(nums == null) 9 return res; 10 if( nums.length == 0){ 11 res.add(new ArrayList<Integer>()); 12 return res; 13 } 14 List<Integer> list = new ArrayList<>(); 15 list.add(nums[0]); 16 res.add(new ArrayList<Integer>(list)); 17 18 for(int i=1;i<nums.length;i++){ 19 int size1 = res.size(); 20 for(int j=0;j<size1;j++){ 21 int size2 = res.get(0).size(); 22 for(int k=0;k<=size2;k++){ 23 ArrayList<Integer> temp = new ArrayList<>(res.get(0)); 24 temp.add(k,nums[i]); 25 res.add(temp); 26 } 27 res.remove(0); 28 } 29 } 30 return res; 31 } 32 }