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],
]

带回溯的递归。(带回溯没法用循环实现)

class Solution {
public List<List<Integer>> combine(int n, int k) {
result = new ArrayList<>();
List<Integer> ans = new ArrayList<Integer>();
dfs(ans,n,k,1);
return result;
} void dfs(List<Integer> ans, int n, int k, int depth){
if(ans.size()==k) {
List<Integer> new_ans = new ArrayList<Integer>(ans);
result.add(new_ans);
return;
}
if(depth>n){
return;
} ans.add(depth);
dfs(ans,n,k,depth+1);
ans.remove(ans.size()-1);
dfs(ans,n,k,depth+1); } private List<List<Integer>> result;
}

最新文章

  1. 常用的Javascript设计模式
  2. Python体验(09)-图形界面之Pannel和Sizer
  3. Arcgis Server发布服务
  4. State Threads——异步回调的线性实现
  5. [SQL]查询及删除重复记录的SQL语句
  6. web前端开发工具HBuilder使用技巧之快捷键
  7. jdownload的使用
  8. JavaBean简单及使用
  9. 【阿里云产品公测】离线归档OAS,再也不用担心备份空间了
  10. Direct3D-3 四元数
  11. COJ 2135 Day10-例1
  12. python爬虫实战1
  13. VPS服务器下的centos网卡配置详解……
  14. Mac上面Mov转gif
  15. centos 6.9安装zabbix 3.0
  16. Minfilter过滤框架
  17. Hibernate学习——API学习
  18. Postgresql数据库部署之:Postgresql 存在session 会话不能删除数据库
  19. iOS8之后搜索框的常规实例
  20. iptables防护CC和DDos和PPTP穿透脚本

热门文章

  1. (转)mysql基础命令
  2. python3笔记七:break和continue语句
  3. EPPlus生成Excel表格(只支持2007及以上)
  4. Python 抓取数据存储到Redis中
  5. 1.1 DAL数据访问层
  6. golang context学习记录1
  7. Kettle使用教程之Job使用
  8. Group By查询
  9. Linux日志筛选命令
  10. 函数对象的apply()和call()方法