和之前的那篇permutation类似,同样的递归思想
package Level3;
import java.util.ArrayList;
/**
* 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 S77 {
public static void main(String[] args) {
System.out.println(combine(4, 2));
}
public static ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> list = new ArrayList<Integer>();
rec(ret, list, 1, n, k);
return ret;
}
// 和那道permutation的题目类似,一个思想
// 递归找combination
public static void rec(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> list, int start, int n, int k){
// base case, 当k为0时,结束递归,添加后返回
if(k == 0){
ret.add(new ArrayList<Integer>(list));
return;
}
// 遍历数组中的每一个数作为第一个元素(i)
// 注意i的终止点,可以举几个具体例子来推出公式
// start: 开始的位置
for(int i=start; i<=n-k+1; i++){
list.add(i);
rec(ret, list, i+1, n, k-1);
list.remove(list.size()-1); // 恢复现场
}
}
}
模板题
public class Solution {
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> al = new ArrayList<Integer>();
rec(n, k, 1, al, ret);
return ret;
}
public void rec(int n, int k, int pos, ArrayList<Integer> al, ArrayList<ArrayList<Integer>> ret){
if(k == 0){
ret.add(new ArrayList<Integer>(al));
return;
}
for(int i=pos; i<=n-k+1; i++){
al.add(i);
rec(n, k-1, i+1, al, ret);
al.remove(al.size()-1);
}
}
}