# leetcode 77. Combinations-排列|递归|非递归|Java|Python

【思路-Java、Python】递归实现

public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
dfs(res, temp, n, k, 1);
return res;
}
private void dfs(List<List<Integer>> res, List<Integer> temp, int n, int k, int m) {
if(k == 0) {
return;
}
for(int i=m; i<=n; i++) {
dfs(res, temp, n, k-1, i+1);
temp.remove(temp.size()-1);
}
}
}
26 / 26 test cases passed. Runtime: 3 ms  Your runtime beats 56.70% of javasubmissions.

class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = []
self.rec(res, 0, n, k, [])
return res
def rec(self, res, i, n, k, temp) :
if k == 0 :
res.append(temp)
return
for j in range(i+1, n+1) :
self.rec(res, j, n, k-1, temp+[j])
26 / 26 test cases passed. Runtime: 88 ms  Your runtime beats 32.21% of pythonsubmissions.

【思路2-Python】非递归实现

class Solution(object):
def combine(self, NN, K):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
result = [[[]]]
for n in range(1,NN+1):
newRes=[[[]]]
for k in range(1,n):
newRes.append(result[k] + [i + [n] for i in result[k-1]])
newRes.append([result[n-1][0] + [n]])
result = newRes
return result[K]
26 / 26 test cases passed. Runtime: 88 ms  Your runtime beats 32.21% of pythonsubmissions.

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode 77. Combinations-排列|递归|非递归|Java|Python 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)