Redian新闻
>
a problem from leetcode: high efficiency algorithm for combinations problem
avatar
a problem from leetcode: high efficiency algorithm for combinations problem# JobHunting - 待字闺中
l*1
1
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],
]
the given api is
public ArrayList> combine(int n, int k)
the solution I got is as follows which is really slow O(n!) and time out at
10,7. So please provide any idea of higher efficiency algorithm for this
one. Thanks in advance
public void combination(ArrayList> result,ArrayList<
Integer> subset,int n, int k){
if(k>n) return;
if(k==0){
Collections.sort(subset);
if(!result.contains(subset))
result.add(subset);
return;
}
for(int i=1;i<=n;i++){
ArrayList newset=new ArrayList();
newset.addAll(subset);
if(!newset.contains(i)){
newset.add(i);
combination(result,newset,n,k-1);
}
}
}
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。