首页 > 代码库 > [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]
.
Solution:
1 public class Solution { 2 public List<List<Integer>> permute(int[] num) { 3 List<List<Integer>> result=new ArrayList<List<Integer>>(); 4 List<Integer> al=new ArrayList<Integer>(); 5 boolean[] flag=new boolean[num.length]; 6 dfs(num,result,al,0,flag); 7 return result; 8 } 9 10 private void dfs(int[] num, List<List<Integer>> result, List<Integer> al, int level,boolean[] flag) {11 // TODO Auto-generated method stub12 if(level>num.length)13 return;14 if(level==num.length){15 result.add(new ArrayList<Integer>(al));16 return;17 }18 for(int i=0;i<num.length;++i){19 if(!flag[i]){20 flag[i]=true;21 al.add(num[i]);22 dfs(num, result, al, level+1, flag);23 al.remove(al.size()-1);24 flag[i]=false;25 }26 } 27 }28 }
[Leetcode] Permutations
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。