77. Combinations - Medium
Given two integers n and k, return all possible combinations of knumbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
use DFS (backtracking)
time = O(k * C(n, k)), space = O( C(n, k) )
class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<>(); dfs(n, k, 1, new ArrayList<>(), res); return res; } public void dfs(int n, int k, int start, List<Integer> list, List<List<Integer>> res) { if(list.size() == k) { res.add(new ArrayList<>(list)); return; } for(int i = start; i <= n; i++) { list.add(i); dfs(n, k, i + 1, list, res); list.remove(list.size() - 1); } } }