Combinations 152
Question
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]]
Solution
Comination模版。注意是从1开始到n。
代码如下:
public class Solution {
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
// write your code here
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(n <= 0 || k <= 0 || n < k){
return result;
}
ArrayList<Integer> list = new ArrayList<Integer>();
combineHelper(result, list, n, k, 1);
return result;
}
private void combineHelper(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int n, int k, int pos){
if(list.size() == k){
result.add(new ArrayList<Integer>(list));
return;
}
for(int i = pos; i <= n; i++){
list.add(i);
combineHelper(result, list, n, k, i + 1);
list.remove(list.size() - 1);
}
}
}