------------------------------------------------
本笔记主要记录在刷九章题目中的思路、问题,以及不能bug-free的原因。
Time Complexity in Coding Interview
• O(1) 极少
• O(logn) 几乎都是二分法
• O(√n) 几乎是分解质因数
• O(n) 高频
• O(nlogn) 一般都可能要排序
• O(n 2 ) 数组,枚举,动态规划
• O(n 3 ) 数组,枚举,动态规划
• O(2 n ) 与组合有关的搜索
• O(n!) 与排列有关的搜索
------------------排列组合问题---------------------
- 适用范围:几乎所有搜索问题,但具体根据题目有改动(比如什么时候去除重复的)
- 特别注意的点:什么时候输出、那些情况跳过。
-
解决重复例子的方法:sort一下再判断下上次取的位置和这次的位置的数一不一样。if(i != pos && nums[i] == nums[i - 1]) continue;
有一些题目,是要求所有方案,这种题目90%是搜索问题,而这90的搜索问题中90%是用递归,另外10%是用非递归写递归。而这些搜索问题一般都是排列组合。
1.---------Permutaions
题意:找一个数组里元素里的全排列,数组中没有重复元素
思路:递归,在一个集合里找数组成排列,那么就需要一个set来记录当前集合里有没有这个数
一刷:WA:原因:没有考虑使用set。
二刷:AC
public class Solution { /* * @param nums: A list of integers. * @return: A list of permutations. */ public List<List<Integer>> permute(int[] nums) { // write your code here List<List<Integer>> res = new ArrayList<>(); List<Integer> permutation = new ArrayList<>(); if (nums.length == 0 || nums == null) { return res; } Set<Integer> set = new HashSet<>(); Helper(nums, res, permutation, set); return res; } private void Helper(int[] nums, List<List<Integer>> res, List<Integer> permutation, Set<Integer> set) { if (permutation.size() == nums.length) { res.add(new ArrayList<Integer>(permutation)); return; } for (int i = 0; i < nums.length; i++) { if (set.contains(nums[i])) continue; set.add(nums[i]); permutation.add(nums[i]); Helper(nums, res, permutation, set); set.remove(nums[i]); permutation.remove(permutation.size() - 1); } } }