Combinations 原题地址:
https://oj.leetcode.com/problems/combinations/
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:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
public class Solution {
private List<List<Integer>> list = new ArrayList<List<Integer>>();
public List<List<Integer>> combine(int n, int k) {
if (k > n || k == 0)
return list;
LinkedList<Integer> _list = new LinkedList<Integer>();
helpCombine(_list, n, 1, k);
return list;
}
private void helpCombine(LinkedList<Integer> _list, int n, int idx, int k) {
if (k == 0) {
LinkedList<Integer> temp = (LinkedList<Integer>) _list.clone();
list.add(temp);
return;
}
if (idx > n)
return;
if (idx + k == n+1) {
LinkedList<Integer> temp = (LinkedList<Integer>) _list.clone();
for (int i = idx; i <= n; i++) {
temp.add(i);
}
list.add(temp);
return;
}
_list.add(idx);
helpCombine(_list, n, idx+1, k-1);
_list.pollLast();
helpCombine(_list, n, idx+1, k);
}
}