You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new LinkedList<>();
if (n < 1 || k < 1 || n < k) return res;
List<Integer> tmp = new LinkedList<>();
dfs(res, tmp, n, k, 1);
return res;
}
public void dfs(List<List<Integer>> res, List<Integer> tmp, int n, int k, int start) {
if (tmp.size() == k) {
res.add(new LinkedList<>(tmp));
return;
}
for (int i = start; i <= n; ++i) {
tmp.add(i);
dfs(res, tmp, n, k, i + 1);
tmp.remove(tmp.size() - 1);
}
}
}
Given a collection of distinct integers, return all possible permutations.
Example:
这题跟46. Permutations很像,使用DFS+回溯法的思想来解。不同的是or循环的初始条件。
相似题目:
参考资料:
The text was updated successfully, but these errors were encountered: