[LeetCode][Java] Combinations
来源:互联网 发布:mac os 创建文件夹 编辑:程序博客网 时间:2024/06/11 19:09
题目:
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个数字的所有的组合。
比方说,
如果n=4 and k=2,解为:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
算法分析:
用一个循环递归处理子问题。
AC代码:
public class Solution { public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(n<=0 || n<k) return res; helper(n,k,1,new ArrayList<Integer>(), res); return res; } private void helper(int n, int k, int start, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> res) { if(item.size()==k) { res.add(new ArrayList<Integer>(item)); return; } for(int i=start;i<=n;i++) // try each possibility number in current position { item.add(i); helper(n,k,i+1,item,res); // after selecting number for current position, process next position item.remove(item.size()-1); // clear the current position to try next possible number } }}
0 0
- [Leetcode] Combinations (Java)
- [LeetCode][Java] Combinations
- [leetcode-77]Combinations(java)
- 【leetcode】77. Combinations【java】
- leetcode JAVA Combinations 难度系数3 3.26
- LeetCode: Combinations
- LeetCode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [LeetCode] Combinations
- Leetcode: Combinations
- LeetCode Combinations
- [Leetcode] Combinations
- [Leetcode] Combinations
- [leetcode] Combinations
- [LeetCode]Combinations
- [leetcode]Combinations
- LeetCode-Combinations
- H264编码原理以及I帧B帧P帧
- 凸包初学(POJ1113)
- 银行储蓄系统
- 【bzoj1509】 NOI2003 逃学的小孩 树的直径
- Length of Last Word
- [LeetCode][Java] Combinations
- 最长回文子串
- Java对象赋值原理详解(下)附实例源码
- tomcat7和jetty启动的pom.xml配置
- 禁止浏览器中双击选中元素的解决方法
- webrtc ios 平台下载 代码编译
- 各种排序算法的比较
- c++课程设计——————银行系统
- 类和对象