lintcode-medium-Combinations
2016-03-16 08:29
344 查看
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]]
思路还是一样的,回溯算法,只是判断条件稍微不通而已
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 Solution { /** * @param n: Given the range of numbers * @param k: Given the numbers of combinations * @return: All the combinations of k numbers out of 1..n */ public List<List<Integer>> combine(int n, int k) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); if(n < 1 || k > n) return result; List<Integer> line = new ArrayList<Integer>(); helper(result, line, n, k, 1); return result; } public void helper(List<List<Integer>> result, List<Integer> line, int n, int k, int start){ if(line.size() == k){ result.add(new ArrayList<Integer>(line)); return; } for(int i = start; i <= n; i++){ line.add(i); helper(result, line, n, k, i + 1); line.remove(line.size() - 1); } return; } }
相关文章推荐
- 再谈百度:KPI、无人机,以及一个必须给父母看的案例
- 欢迎使用CSDN-markdown编辑器
- [HNOI2012]与非 解题报告
- (四)ExtJs自定义弹出框(show)
- thread
- POJ 3187 Backward Digit Sums (全排列)
- ORA-39143: 转储文件可能是原始的导出转储文件
- [3.16]竞赛入门经典,习题2-6
- IMP-00032:SQL 语句超过缓冲区长度的问题解决
- Docker 入门到实践笔记2
- POJ 3061 Subsequence (尺取)
- 2016写点blog
- 电子邮件营销在数字营销浪潮中扮演关键角色
- bzoj2434: [Noi2011]阿狸的打字机
- HDOJ 1220 Cube (数学)
- Windows Server 2008 R2配置JSP网站无法访问
- HDOJ 1027 Ignatius and the Princess II (DFS全排列)
- iOS 页面跳转传值,属性传值,代理传值,代码块传值,单例传值,通知传值
- CSS 有趣的边框
- PAT 1026