[leetcode-77]Combinations(java)
1819 ワード
问题详述: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], ]
分析:これは明らかに再帰的に使用されていますが、結果はTLEができるかどうか迷っていましたが、結果は悪くないと思います.
コードは次のとおりです:288 ms
For example, If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
分析:これは明らかに再帰的に使用されていますが、結果はTLEができるかどうか迷っていましたが、結果は悪くないと思います.
コードは次のとおりです:288 ms
public class Solution {
private void solve(List> res,List tmpList,int n,int k,int index){
if(tmpList.size()==k){
res.add(new LinkedList<>(tmpList));
return;
}
int size = tmpList.size();
for(int i = index;i<=n-k+size+1;i++){
tmpList.add(i);
solve(res,tmpList,n,k,i+1);
tmpList.remove(size);
}
}
public List> combine(int n, int k) {
List> res = new LinkedList<>();
List tmpList = new LinkedList<>();
solve(res,tmpList,n,k,1);
return res;
}
}