Leetcode 题解 - 搜索--Backtracking(13):Permutations 全排列
2019-05-27 11:25
239 查看
[LeetCode] Permutations 全排列
Given a collection of distinct integers, return all possible permutations.
Example:
[code]Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
这道题是求全排列问题,给的输入数组没有重复项,这跟之前的那道 Combinations 和类似,解法基本相同,但是不同点在于那道不同的数字顺序只算一种,是一道典型的组合题,而此题是求全排列问题,还是用递归DFS来求解。这里我们需要用到一个visited数组来标记某个数字是否访问过,然后在DFS递归函数从的循环应从头开始,而不是从level开始,这是和 Combinations 不同的地方,其余思路大体相同。这里再说下level吧,其本质是记录当前已经拼出的个数,一旦其达到了nums数组的长度,说明此时已经是一个全排列了,因为再加数字的话,就会超出。还有就是,为啥这里的level要从0开始遍历,因为这是求全排列,每个位置都可能放任意一个数字,这样会有个问题,数字有可能被重复使用,由于全排列是不能重复使用数字的,所以我们需要用一个visited数组来标记某个数字是否使用过,代码如下:
[code]class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> permutes = new ArrayList<>(); List<Integer> permuteList = new ArrayList<>(); boolean[] hasVisited = new boolean[nums.length]; help(permuteList,permutesm, hasVisited, nums); return permutes; } private void help(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums){ //次数一定是n*n个list 所以每带nums.length就添加N组到我们要返回的list中 //这个思路和下面重复利用visited是一个道理 if(permuteList.size() == nums.length){ permutes.add(new ArrayList<>(permuteList));// 一定是这种写法 return; } //for循环遍历每个数组 这里是visited 毕竟用过的不能再用l for(int i=0; i < visited.length; i++){ if(visited[i]) continue; visited[i] = true; permuteList.add(nums[i]); //继续遍历每个数组 用过的不能再用, //!!!!当然是仅限单词for循环的子递归函数里面 逐渐逐渐不能用了1 2 3 4 5 6 7 8 9 help(permuteList, permutes, visited, nums); permuteList.remove(permuteList.size() - 1); visited[i] = false; } } }
相关文章推荐
- Leetcode 题解 - 搜索--Backtracking(14):全排列2
- Leetcode 题解 - 搜索--Backtracking(21):分割字符串使得每个部分都是回文数
- Leetcode 题解 - 搜索--Backtracking(17):1-9 数字的组合求和
- Leetcode 题解 - 搜索--Backtracking(15):组合
- Leetcode 题解 - 搜索--Backtracking(19):子集合
- Leetcode 题解 - 搜索--Backtracking(20):含有相同元素求子集
- LeetCode题解-13-Roman to Integer
- leetcode:Permutations (序列所有排列)【面试算法题】
- Leetcode 079 搜索单词 Python C++ 史上最详细题解系列
- leetcode Permutations II 无重全排列
- 013_LeetCode_13 Roman to Integer 题解
- LeetCode题解:Permutations
- 【LeetCode题目记录-13】二分搜索排序后的二维数组
- LeetCode (18) Permutations I & II (排列一、二)
- [leetcode] permutations 排列
- LeetCode:Permutations, Permutations II(求全排列)
- [leetcode 46] Permutations------数组中元素的所有排列组合集合
- LeetCode:Permutations(求全排列)
- **(leetcode_backtracking)Permutations
- 【题解】【排列组合】【回溯】【Leetcode】Gray Code