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], ]比较模板化的题目,典型的DFS问题,有好多种题目可以套用类似的模板。
public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> current = new ArrayList<Integer>(); if(n < k) return result; comb(n, 1, k, current, result); return result; } private void comb(int n, int beg, int k, List<Integer> current, List<List<Integer>> result) { if(k == 0) { result.add(new ArrayList<Integer>(current)); } else { if(beg > n) return; for(int i = beg; i <= n; i++) { current.add(i); comb(n, i+1, k-1, current, result); current.remove(current.size() - 1); } } }
没有评论:
发表评论