【LeetCode-面试算法经典-Java实现】【077-Combinations(组合数)】
2015-07-30 06:38
746 查看
【077-Combinations(组合数)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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], ]
题目大意
给定两个数n和k,求从1-n中k个数的所有组合。解题思路
采用递归分治法进行求解,详见代码。代码实现
算法实现类import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Solution { private List<List<Integer>> result; private List<Integer> l; public List<List<Integer>> combine(int n, int k) { result = new LinkedList<>(); if (n > 0 && k > 0 && n >= k) { l = new LinkedList<>(); combine(1, n, k); } return result; } /** * 求组合 * * @param start 可选择的数开始位置 * @param end 可选择的数的结束位置 * @param num 在[start, end]中选择的数的数目 */ private void combine(int start, int end, int num) { if (num == 0) { List<Integer> tmp = new ArrayList<>(); for(Integer i: l) { tmp.add(i); } result.add(tmp); return; } int endFirst = end - num + 1; // 第一个数可以选择的最大值 for (int i = start; i <= endFirst; i++) { l.add(i); combine(i + 1, end, num - 1); l.remove(new Integer(i)); } } }
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。特别说明
欢迎转载,转载请注明出处【/article/1343418.html】
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【075-Sort Colors (颜色排序)】
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】
- 黑马程序员 日记(六)
- 黑马程序员 日记(五)
- 黑马程序员 日记(四)
- 黑马程序员 日记(三)
- 黑马程序员 学习日记(二)
- 黑马程序员----JAVA基础----面向对象基础篇
- 黑马程序员——集合框架collection集合接口及List子类
- 面试题:用一条sql语句查询出“每门”课程都大于80分的学生姓名
- 加油吧 实习生!职场菜鸟们
- 程序员必备技能
- 黑马程序员------OC类的封装 继承 多态
- 黑马程序员------OC @property 关键字及构造方法的使用
- 黑马程序员------oc之面向对象特性 封装、多态、继承等
- 黑马程序员——System类常用方法及流对象操作规律
- 那些年的面试总结
- 数据库面试题——比赛数据查询
- 程序员(攻城狮)成长之路
- (剑指Offer)面试题45:圆圈中最后剩下的数字