Problem
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example
For example,
If n = 4 and k = 2, a solution is:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]Note
题目为求从1到n的自然数里取k个数的所有组合全集。使用递归的模板,建立helper函数。
模板如下:void helper(range S, target T, start A, tempArray B) { if (B met T or other requirement) { res.add(B); return; } for (int i starts from A in S) { tempArray C = new tempArray (B); C.add(i); helper(S, T-i, i+1, C); }}
也可以不建立新的tempArray C,而是递归调用helper之后删去B中最后一个元素:
void helper(range S, target T, start A, tempArray B) { if (B met T or other requirement) { res.add(B); return; } for (int i starts from A in S) { B.add(i); helper(S, T-i, i+1, C); B.remove(B.size()-1); }}
Solution
public class Solution { List
> res = new ArrayList
>(); public List
> combine(int n, int k) { helper(n, k, 1, new ArrayList ()); return res; } private void helper(int n, int k, int start, List pre) { if (pre.size() == k) { res.add(pre); return; } for (int i = start; i <= n; i++) { List cur = new ArrayList (pre); cur.add(i); helper(n, k, i+1, cur); } }}