Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList();
        List<Integer> tmp = new ArrayList();
        dfs(n, k, 1, 0, tmp, result);
        return result;
    }
    // start,开始的数, cur,已经选择的数目
    private static void dfs(int n, int k, int start, int cur,
                            List<Integer> tmp, List<List<Integer>> result) {
        if (cur == k) {
            result.add(new ArrayList(tmp));
        }
        for (int i = start; i <= n; ++i) {
            tmp.add(i);
            dfs(n, k, i + 1, cur + 1, tmp, result);
            tmp.remove(tmp.size() - 1);
        }
    }
}

backtracking的变种

02-01 13:25