三刷 06/2022
Version #1 DFS
Time O(KN!/(K!(N-K)!)) -> O(K) time for each result to copy the array
Space O(N!/(K!(N-K)!)) for the output, if output is not included, then O(K) for keep track of the path
Runtime: 21 ms, faster than 77.65% of Java online submissions for Combinations.
Memory Usage: 43.5 MB, less than 94.06% of Java online submissions for Combinations.
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
dfs(1, k, n, new ArrayList<>(), result);
return result;
}
private void dfs(int start, int k, int n, List<Integer> path, List<List<Integer>> result) {
if (k == 0) {
result.add(new ArrayList<>(path));
return;
}
for (int i = start; i <= n; i++) {
path.add(i);
dfs(i + 1, k - 1, n, path, result);
path.remove(path.size() - 1);
}
}
}
5mins bug free
最神的是前天面试刚刚面了这个题
50.25 %
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
if (n <= 0 || k <= 0) return result;
dfs(1, n, k, new ArrayList<>(), result);
return result;
}
private void dfs(int start, int n, int k, List<Integer> path, List<List<Integer>> result) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
if (start > n) {
return;
}
for (int i = start; i <= n; i++) {
path.add(i);
dfs(i + 1, n, k, path, result);
path.remove(path.size() - 1);
}
}
}
一刷
两个bug
1. helper函数把下一层的start index写成了 start + 1 而不是 i + 1
2. corner case n <= k 把 n == k 给排除了, 但实际上n == k 是可以work的
39.04%
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (n <= 0 || k <= 0 || n < k) return result;
helper(n, k, 1, new ArrayList<Integer>(), result);
return result;
}
public void helper(int n, int k, int start, List<Integer> path, List<List<Integer>> result) {
if (k == 0) {
result.add(new ArrayList<Integer>(path));
return;
}
for (int index = start; index <= n; index++) {
path.add(index);
helper(n, k - 1, index + 1, path, result);
path.remove(path.size() - 1);
}
}
}
No comments:
Post a Comment