Combinations
来源:互联网 发布:三菱plc编程电缆 编辑:程序博客网 时间:2024/06/03 13:17
Q:
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],]
Solution:
Note: We need to remove the last added element from the list, since we need a room to try new numbers.
public class Solution { List<List<Integer>> combines;public List<List<Integer>> combine(int n, int k) { combines = new ArrayList<List<Integer>>(); if (n <= 0 || k <= 0 || n < k) return combines; for (int i = 1; i <= n-k+1; i++) { ArrayList<Integer> list = new ArrayList<Integer>(); subCombine(i, n, k, list); } return combines; } public void subCombine(int start, int end, int k, ArrayList<Integer> list) { list.add(start); if (list.size() == k) { List<Integer> addlist = new ArrayList<Integer>(list); combines.add(addlist); return; } for (int i = start+1; i <= end; i++) { subCombine(i, end, k, list); 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
- java删除目录下的文件失败
- 【BestCoder】 HDOJ Operation the Sequence
- Struts1与Struts2比较(完整版)
- 第一次微信开发及其他
- 大程序结构
- Combinations
- 网易研发工程师(移动端游戏)—暑期实习生电面题目 2014年5月14日
- 京东一道java题目
- 2014.10.12总结
- C++成员函数指针
- 【Algorithm】快速排序--算法实现
- 4.4 创建 Windows Forms 应用程序
- .net项目中连接字符串的配置
- CentOS开启FTP及配置用户