Permutation I,II
来源:互联网 发布:vmware ubuntu 全屏 编辑:程序博客网 时间:2024/04/29 06:27
还要有多典型的DFS + backtracking,之前写的乱七八糟凑出来的,后来用了这个思想好写多了。所以啊,要掌握思想就得先多看些范例。但是,dp看了这么多,还是好多dp不出来额。。。再接再励吧亲!
注意问interviewer array里面的元素是unique的吗?!
1,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]
.
public class Solution { public List<List<Integer>> permute(int[] num) { List<List<Integer>> res = new ArrayList<>(); List<Integer> list = new ArrayList<>(); boolean[] visited = new boolean[num.length]; helper(res, list, num, visited); return res; } public void helper(List<List<Integer>> res, List<Integer> list, int[] num, boolean[] visited) { if (list.size() == num.length) { res.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < num.length; i++) { if (!visited[i]) { list.add(num[i]); visited[i] = true; //如果不要visited数组,直接call list.contains(i),每个call的复杂度是O(n) helper(res, list, num, visited); list.remove(list.size()-1); visited[i] = false; } } }}
2. 如果array中有重复元素呢? -》重复?先把Array sort
public class Solution { public List<List<Integer>> permuteUnique(int[] num) { if (num == null || num.length == 0) return null; Arrays.sort(num); List<List<Integer>> res = new ArrayList<>(); List<Integer> ls = new ArrayList<>(); boolean[] visited = new boolean[num.length]; helper(res, ls, num, visited); return res; } public void helper(List<List<Integer>> res, List<Integer> list, int[] num, boolean[] visited){ if(list.size() == num.length){ res.add(new ArrayList<Integer>(list)); return; } for (int i = 0; i < num.length; i++) { if (visited[i] || (i > 0 && !visited[i-1] && num[i] == num[i-1])) { continue; } list.add(num[i]); visited[i] = true; helper(res, list, num, visited); visited[i] = false; list.remove(list.size() - 1); } }}
0 0
- Leetcode Permutation I & II
- permutation I & II
- Permutation I,II
- [LintCode] Permutation Index I & Permutation Index II
- Leetcode Palindrome Permutation I & II
- Permutation II
- Permutation II
- Permutation I
- LeetCode之Permutation、Permutation II
- leetcode -- Permutation & Permutation II--重点
- [Leetcode] Permutation II
- Leetcode Permutation II
- Permutation II @leetcode
- [LeetCode] Permutation II
- Leetcode -- Permutation II
- Permutation II--LeetCode
- 16. permutation II
- [LeetCode267]Palindrome Permutation II
- 黑马程序员——面向对象程序设计
- [Leetcode]Flatten Binary Tree to Linked List (三种方法)
- 如何实现servlet的线程安全
- 华为荣耀3C最新版ROM的root,(4.7.1和4.8.1等等通用方法)
- servlet是只有一个实例吗
- Permutation I,II
- opencv中遍历图像(IplImage格式)
- JAVA学习笔记——多线程
- 2014-10-30
- android内存检测
- JPA使用mysql的时候创建varchar型列使用utf8
- window+Apache 配置虚拟主机(2)
- 算法比赛
- App Store Review Guidlines