Combinations
来源:互联网 发布:企业危机网络 编辑:程序博客网 时间:2024/06/06 16:59
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],]
枚举出所有的长度为k的子集,一般都用递归+深度搜索
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> solution = new ArrayList<List<Integer>>(); List<Integer> path = new ArrayList<Integer>(); helper(solution,path,1,n,k); return solution; } public void helper(List<List<Integer>> solu,List<Integer> path,int from,int n, int k){if(path.size() == k){List<Integer> lst = new ArrayList<Integer>(path);solu.add(lst);return;}else {for(int i = from;i <= n;i++){path.add(i);helper(solu,path,i+1,n,k);path.remove(path.size()-1);}}}}
但是效率有点低的,只打败了15%,能不能进行优化呢?于是我们增加一些条件
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> solution = new ArrayList<List<Integer>>(); if(k <= n && k >= 1){ List<Integer> path = new ArrayList<Integer>(); helper(solution,path,1,n,k); } return solution; } public void helper(List<List<Integer>> solu,List<Integer> path,int from,int n, int k){if(path.size() == k){List<Integer> lst = new ArrayList<Integer>(path);solu.add(lst);}else {for(int i = from;i <= n;i++){path.add(i);helper(solu,path,i+1,n,k);path.remove(path.size()-1);}}}}
此时打败了76.46%0 0
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Combinations
- combinations
- Combinations
- Combinations
- Combinations
- Combinations
- Android Studio常用插件—— JsonOnlineViewer
- NOIP2007 提高组 复赛 count 统计数字
- 设计模式六大原则之--里氏替代原则(LSP)
- java项目转web
- Best Time to Buy and Sell Stock II
- Combinations
- uml(unified modeling language)用例图、类图、序列图详解
- SVN同步之Android studio 与新浪云(SAE)
- Ajax的GET与POST和Ajax文件上传进度条
- JAVA如何在窗口设置背景图片
- 75篇关于Tomcat源码和机制的文章
- 基于arcgis的城市放射状指数研究
- 设计模式六大原则之--单一职责原则(SRP)
- easyui acceptChanges 更新无法获取数据