还要有多典型的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);
}
}
}