首页 > 代码库 > LeetCode Permutations
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 3 public List<List<Integer>> permute(int[] num) { 4 List<List<Integer>> lastList=new ArrayList<List<Integer>>(); 5 List<List<Integer>> currList=new ArrayList<List<Integer>>(); 6 if (num==null) { 7 return lastList; 8 } 9 10 List<Integer> eleList=new ArrayList<>();11 eleList.add(num[0]);12 lastList.add(eleList);13 14 if (num.length==1) {15 return lastList;16 }17 for (int i = 1; i < num.length; i++) {18 for (List<Integer> l : lastList) {19 currList.addAll(insertList(num[i], l));20 21 }22 lastList.clear();23 lastList.addAll(currList);24 currList.clear();25 }26 return lastList;27 28 }29 30 private List<List<Integer>> insertList(int num,List<Integer> list) {31 List<List<Integer>> retNew=new ArrayList<List<Integer>>();32 33 for (int i = 0; i <= list.size(); i++) {34 List<Integer> currlist=new ArrayList<>();35 currlist.addAll(list);36 currlist.add(i, num);37 retNew.add(currlist);38 currlist=null;39 }40 return retNew;41 42 }43 }
LeetCode Permutations
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。