LeetCode-77.Combinations
来源:互联网 发布:一点一点吃干抹净淘宝 编辑:程序博客网 时间:2024/05/24 11:15
题目描述
给定两个整数n和k,求1.2.3.4……n中所有可能出现的k个数的组合。如果n=4,k=2,则答案为[ [2,4],[3,4],[2,3],[1,2],[1,3],[1,4] ]。
解题思路
采用递归的方式解决,上面地答案简单整理一下可以看成是1,2;1,3;1,4;2,3;2,4;3,4;对于每个位置的数利用递归函数求解包含与他右边距离为1地数地解,然后求解距离为2,然后依次递增,直到当前数+step(间隔)+remain(剩余地数字个数)-2大于n,则跳出当前地循环。
代码
public class Solution { List<List<Integer>> result=new ArrayList<List<Integer>>(); //这里是无法List<List<Integer>> result=new ArrayList<ArrayList<Integer>>(); 简单地理解可以是左边地List<List<Integer>>变量可以添加LinkedList<Integer>变量,而右边地变量ArrayList<ArrayList<Integer>>变量却不能添加。 List<Integer> tem=new ArrayList<Integer>(); public List<List<Integer>> combine(int n, int k) { if(k<=0 || n<=0 || k>n) return result; for(int i=1;i<=n-k+1;i++){ combineCore(i,k,n); } return result; } //weizhi shengyugeshu step private void combineCore(int point,int remain,int n){ if(remain==1){ tem.add(point); result.add(new ArrayList<Integer>(tem)); tem.remove(tem.size()-1); return; } for(int step=1;point+step+remain-2<=n;step++){ tem.add(point); combineCore(point+step,remain-1,n); tem.remove(tem.size()-1); } }}
有关列表转换地问题(https://stackoverflow.com/questions/24796273/incompatible-types-list-of-list-and-arraylist-of-arraylist)
阅读全文
0 0
- LeetCode 77. Combinations
- [LeetCode]77.Combinations
- LeetCode --- 77. Combinations
- [Leetcode] 77. Combinations
- [leetcode] 77.Combinations
- leetCode 77.Combinations (组合)
- [leetcode] 77. Combinations
- 77. Combinations LeetCode
- <LeetCode OJ> 77. Combinations
- [LeetCode]77. Combinations
- leetcode 77. Combinations
- LeetCode *** 77. Combinations
- leetcode 77. Combinations
- LeetCode 77. Combinations
- LeetCode-77.Combinations
- LeetCode 77.Combinations
- [LeetCode]problem 77. Combinations
- [LeetCode] 77. Combinations
- react-native 屏幕尺寸和文字大小适配
- 51单片机之UCOSII系统移植(1)
- MDK生成bin文件
- 使用Vue-cli下载一个以webpack打包的vue模板
- js 点击列表li,获得当前li的id
- LeetCode-77.Combinations
- 设计模式之单例模式
- kNN近邻算法
- LeetCode
- Ruby 循环控制
- JSTL之数字、日期格式化<fmt:formatNumber/>、<fmt:formatDate/>
- mysql主从复制,数据量大, 高并发时,出现数据不一致
- 解决MVC Json序列化的循环引用问题/EF Json序列化循引用问题(Newtonsoft.Json)
- 同步/异步,阻塞/非阻塞