首页 > 代码库 > 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]
.
思路分析:这题是Permutations II问题的简化版本,直接用DFS搜索做,不必判断重复数字的情况。详细题解分析可以参考 LeetCode Permutations II
AC Code
public class Solution { public List<List<Integer>> permute(int[] num) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(num == null || num.length == 0){ return res; } Arrays.sort(num); List<Integer> state = new ArrayList<Integer>(); dfs(res, state, num, new boolean[num.length]); return res; } void dfs(List<List<Integer>> res, List<Integer> state, int [] num, boolean [] used){ if(state.size() == num.length){ res.add(new ArrayList(state));//add a copy return; } for(int i = 0; i < num.length; i++){ //if(i > 0 && !used[i-1] && num[i] == num[i-1]) continue;// judge duplicate number if(!used[i]){ state.add(num[i]); used[i] = true; dfs(res, state, num, used); state.remove(state.size() - 1); used[i] = false; } } } }
LeetCode Permutations
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。