Combinations
来源:互联网 发布:u盘安装ubuntu系统安装 编辑:程序博客网 时间:2024/05/16 12:28
Given two integers n and k, return all possible combinations ofk 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来求解这个问题
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<>(); if(n <= 0 || k > n) return res; List<Integer> list = new ArrayList<>(); dfs(n,k,1,list,res); return res; } public void dfs(int n, int k, int start, List<Integer> list, List<List<Integer>> res){ if(list.size() == k) { res.add(new ArrayList<>(list)); return; } for(int i = start; i <= n; i++){ list.add(i); //添加一个新的元素 dfs(n,k,i+1,list,res); list.remove(list.size()-1); // 删除刚才添加进去的元素 } }}
阅读全文
0 0
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- combinations
- Combinations
- Combinations
- Combinations
- Combinations
- I/O多路转接之epoll
- android手势方向的判断工具类,超简单
- hadoop学习2 记录配置hadoop环境的那些坑
- 【es6】 let & const
- CSS思维导图
- Combinations
- Android NDK线程篇(四)
- wormhole-section1.3
- hadoop学习3 查找块的位置
- 两数组的交||
- 模板
- 我的第一条博文
- const类型的成员函数
- JDBC连接池