java|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], ]
使用DFS,与Combination Sum类似的思路,只是判断size即可。
public List> combine(int n, int k) {
ArrayList> at=new ArrayList>();
if(n<=0||n lt=new ArrayList();
dfs(n,k,1,lt,at);
return at;
}
private void dfs(int n,int k,int start,List lt,ArrayList> at){
if(lt.size()==k){
at.add(new ArrayList(lt));
return;
}
for(int i=start;
i<=n;
i++){
lt.add(i);
dfs(n,k,i+1,lt,at);
lt.remove(lt.size()-1);
}
}
【java|Combinations】
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 事件代理
- Java|Java OpenCV图像处理之SIFT角点检测详解
- java中如何实现重建二叉树
- 数组常用方法一
- 【Hadoop踩雷】Mac下安装Hadoop3以及Java版本问题
- Java|Java基础——数组
- RxJava|RxJava 在Android项目中的使用(一)
- java之static、static|java之static、static final、final的区别与应用
- Java基础-高级特性-枚举实现状态机