# 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

LeetCode77——Combinations 题意： 两个数字n和k，找出所有这样的组合： 1.组合中有k个数字 2.组合是递增 3.组合中的数字是{1,2,3,....n} 的子集 ...

## 【LEETCODE】77-Combinations [Python]

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For exam...

## [LeetCode]77.Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

## 【leetcode】第47题 Permutations II(非递归法)题目+解析+代码

【题目】 Given a collection of numbers that might contain duplicates, return all possible unique pe...
• buppt
• 2017-08-22 15:00
• 26

## [leetcode-７７]Combinations(java)

• zdavb
• 2015-08-05 20:57
• 459

## CSDN博客积分规则

• buppt
• 2017-08-09 14:08
• 184

## 【LeetCode with Python】 Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For examp...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)