###### 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.

#### LeetCode77——Combinations

2015-11-17 21:21:10

#### 77 Combinations

2015-10-25 16:20:02

#### 【leetcode】【77】Combinations

2015-11-26 14:45:38

#### LeetCode 77. Combinations 解题报告

2016-02-18 14:03:18

#### 【LEETCODE】77-Combinations [Python]

2016-01-07 16:57:28

#### Python使用combinations实现排列组合

2017-07-30 17:25:14

#### <LeetCode OJ> 77. Combinations

2016-03-09 15:35:14

#### python之permutations和combinations的区别

2011-07-05 13:35:36

#### LeetCode Combinations

2016-01-23 21:07:58

#### Combinations 求1至n中所有K位数的所有组合

2017-06-14 19:22:50

## 不良信息举报

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