LeetCode OJ算法题(七十七):Combinations
来源:互联网 发布:武汉大学网络维修电话 编辑:程序博客网 时间:2024/04/28 18:36
题目:
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],]解法:
题目要求输出1~n的所有含k个元素组合,很容易想到利用递归的思路,将问题分解为更小的子问题。
1~n的组合可以分为含有n,和不含有n,即(n-1,k-1)的集合中加上n,以及(n-1,k)的集合,将两部分合并即为结果
import java.util.ArrayList;import java.util.List;public class No77_Combinations {public static void main(String[] args){System.out.println(combine(4, 2));}public static List<List<Integer>> combine(int n, int k) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if(n < 1 || n < k) return ret; if(k == 0) return ret; if(k == n) { List<Integer> element = new ArrayList<Integer>(); for(int i=1;i<=n;i++) element.add(i); ret.add(element); return ret; } List<List<Integer>> withN = combine(n-1, k-1); if(withN.size() == 0){ List<Integer> element = new ArrayList<Integer>(); element.add(n); ret.add(element); } for(int i=0;i<withN.size();i++){ withN.get(i).add(n); ret.add(withN.get(i)); } List<List<Integer>> withoutN = combine(n-1, k); for(int i=0;i<withoutN.size();i++){ ret.add(withoutN.get(i)); } return ret; }}
0 0
- LeetCode OJ算法题(七十七):Combinations
- LeetCode OJ算法题(十八):Letter Combinations of a Phone Number
- LeetCode OJ 之 Combinations (组合)
- 【LeetCode OJ】Combinations
- LeetCode OJ:Combinations
- LeetCode OJ - Combinations
- LeetCode OJ Combinations
- <LeetCode OJ> 77. Combinations
- LeetCode OJ-77.Combinations
- Leetcode OJ 77 Combinations [Medium]
- LeetCode算法题目:Combinations
- LeetCode OJ算法题(四十五):Permutations
- LeetCode OJ算法题(四十八):Anagrams
- LeetCode OJ算法题(七十八):Subsets
- Android开发笔记(七十七)图片缓存算法
- LeetCode算法题之Letter Combinations of a Phone Number
- LeetCode(77) Combinations
- LeetCode OJ算法题(一):Two Sum
- 横竖屏切换android:configChanges
- ora-01031:insufficient privileges解决方法总结
- android 打开File Explorer里的data文件夹
- 大多数初创公司是如何把市场营销搞砸的
- Zookeeper与Curator
- LeetCode OJ算法题(七十七):Combinations
- linux网络基础
- pep8 python编码规范中文版
- uva11093 Just Finish it up(思路)
- LeetCode之旅(12)
- JQuery Study Notes— A small demo for Smooth Animated Menu
- .NET程序性能的基本要领
- work_weipa_下拉刷新+上拉加载
- SQL生成n位随机字符串