Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
Solution:
Use DFS to traverse all permutations.
When we find the candidate list has length of k, we put it into the result and stop adding new elements.
Code:
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result = new ArrayList<>(); helper(n, k, result, new ArrayList<Integer>(), 1); return result; } public void helper(int n, int k, List<List<Integer>> result, List<Integer> list, int start) { if (list.size() == k) { result.add(new ArrayList<>(list)); return; } for (int i = start; i <= n; i++) { list.add(i); helper(n, k, result, list, i + 1); list.remove(list.size() - 1); } } }