[LeetCode-JAVA] 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]
思路:最近都是在做DFS有关的,第一时间的反应就是可以用DFS的思想,唯一需要注意的就是在遍历的过程中,要查看是否是已经被选择的数字,这里用Set来进行排查,思路比较简单。
代码:
public List<List<Integer>> permute(int[] nums) { List<List<Integer>> req = new ArrayList<List<Integer>>(); List<Integer> temp = new ArrayList<Integer>(); Set<Integer> set = new HashSet<Integer>(); dfs(req, temp, set, nums, 0); return req; } public void dfs(List<List<Integer>> req, List<Integer> temp, Set<Integer> set, int[] nums, int level){ //level记录遍历的层数 if(level == nums.length){ req.add(new ArrayList<Integer>(temp)); return; } for(int i = 0 ; i < nums.length ; i++){ if(set.contains(nums[i])) continue; temp.add(nums[i]); set.add(nums[i]); level++; dfs(req, temp, set, nums, level); level--; set.remove(temp.get(temp.size()-1)); temp.remove(temp.size() - 1 ); } }