首页 > 代码库 > 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]
.
Have you met this question in a real interview?
Solution:
Use recursive method. This solution is a iterative recursive solution.
1 public class Solution { 2 public List<List<Integer>> permute(int[] num) { 3 int len = num.length; 4 List<List<Integer>> resSet = new ArrayList<List<Integer>>(); 5 List<Integer> curSeq = new ArrayList<Integer>(); 6 boolean[] used = new boolean[len]; 7 Arrays.fill(used,false); 8 Arrays.sort(num); 9 int curIndex = 0;10 curSeq.add(-1);11 while (curIndex!=-1){12 if (curIndex==len){13 List<Integer> temp = new ArrayList<Integer>();14 for (int i=0;i<curSeq.size();i++) temp.add(num[curSeq.get(i)]);15 resSet.add(temp);16 curIndex--;17 continue;18 }19 20 int val = -1;21 if (curSeq.size()>curIndex){22 val = curSeq.get(curIndex);23 if (val!=-1)24 used[val]=false;25 curSeq.remove(curIndex);26 }27 28 boolean find = false;29 for (int i=val+1;i<len;i++)30 if (!used[i]){31 used[i]=true;32 curSeq.add(i);33 curIndex++;34 find = true;35 break;36 }37 38 if (find)39 continue;40 else 41 curIndex--;42 }43 44 return resSet;45 }46 }
Leetcode-Permutations
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。