给定两个整数 n
和 k
,返回 1 ... n
中所有可能的 k
个数的组合。
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
package offer;
import java.util.LinkedList;
import java.util.List;
public class 包含k个元素的组合 {
public static void main(String[] args) {
System.out.println(combine(4,2));
}
public static List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> con = new LinkedList<>();
helper(n,k,1,con,result);
return result;
}
public static void helper(int n,int k,int i,LinkedList<Integer> con,List<List<Integer>> result){
if(con.size()==k){
result.add(new LinkedList<>(con));
}else if(i<=n){
helper(n,k,i+1,con,result);
con.add(i);
helper(n,k,i+1,con,result);
con.removeLast();
}
}
}
总结:其实还是一个求子集的过程 不过在其中的过程的中添加了条件