Given two integers n
and k
. Return all possible combinations of k
numbers out of 1, 2, ... , n
.
Example
Example 1:
Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Example 2:
Input: n = 4, k = 1
Output: [[1],[2],[3],[4]]
Notice
You can return all combinations in any order, but numbers in a combination should be in ascending order.
思路: return all 一看就是recursion,DFS+backtracking
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if(n <= 0 || k <= 0) {
return lists;
}
List<Integer> list = new ArrayList<Integer>();
dfs(n, k, list, lists, 1);
return lists;
}
private void dfs(int n, int k, List<Integer> list, List<List<Integer>> lists, int start) {
if(list.size() == k) {
lists.add(new ArrayList<Integer>(list));
return;
}
for(int i = start; i <= n; i++) {
list.add(i);
dfs(n, k, list, lists, i + 1);
list.remove(list.size() - 1);
}
}
}