wayetan
12/30/2013 - 6:19 AM

## Combinations

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 {
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
if(n < k)
return null;
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(k == 1){
for(int i = 1; i <= n; i++){
ArrayList<Integer> arr = new ArrayList<Integer>();
}
return res;
}
for(int i = n; i>= k; i--){
for(ArrayList<Integer> arr : combine(i - 1, k - 1)){
}
}
return res;
}

public List<List<Integer>> combineAnother(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(k > n || k <= 0) return res;
helper(n, k, 1, new ArrayList<Integer>(), res);
return res;
}
public void helper(int n, int k, int start, List<Integer> path, List<List<Integer>> res) {
if(k < 0) return;
if(k == 0) res.add(path);
for(int i = start; i <= n; i++) {
List<Integer> tmp = new ArrayList<Integer>(path);