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]]
题目大意:给定数字n和k,找出所有1->n中可能的k个数组合
题目难度:Medium
import java.util.*;
/**
* Created by gzdaijie on 16/6/2
*/
public class Solution {
private int n, k;
private List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
ArrayList<Integer> tmp = new ArrayList<>();
combineRecursive(0, tmp);
return result;
}
private void combineRecursive(int count, ArrayList<Integer> tmp) {
if (count == k) {
result.add((ArrayList<Integer>)tmp.clone());
return;
}
int i = count > 0 ? tmp.get(count - 1) + 1 : 1;
for (; i <= n; i++) {
tmp.add(i);
combineRecursive(count + 1, tmp);
tmp.remove(count);
}
}
}