[LeetCode] 77. Combinations_Medium tag: backtracking
2021-07-14 10:18 Johnson_强生仔仔 阅读(18) 评论(0) 编辑 收藏 举报Given two integers n
and k
, return all possible combinations of k
numbers out of the range [1, n]
.
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
Example 2:
Input: n = 1, k = 1 Output: [[1]]
Constraints:
1 <= n <= 20
1 <= k <= n
Update on 10/30/2023, we use permutation 模板,然后相当于判断 nums[i] > temp[-1] 即可,然后当len(temp) == k时,ans.append(temp)
Ideas:
1. 利用backtracking
T: k * C(k, n) => k * n! / k! / (n - k)!
S: k * C(k, n) => k * n! / k! / (n - k)!
Code:
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: nums = [i for i in range(1, n + 1)] ans = [] self.helper(nums, [], ans, k) return ans def helper(self, nums, temp, ans, k): if len(temp) == k: ans.append(temp) elif len(temp) < k: for i in range(len(nums)): if not temp or nums[i] > temp[-1]: self.helper(nums[:i] + nums[i + 1:], temp + [nums[i]], ans, k)
2. 利用subset模板,相当于subset只取len(temp) == k的情况:
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: nums = [i for i in range(1, n + 1)] ans = [] self.helper(nums, [], ans, 0, k) return ans def helper(self, nums, temp, ans, pos, k): if len(temp) == k: ans.append(temp) elif len(temp) < k: for i in range(pos, len(nums)): self.helper(nums, temp + [nums[i]], ans, i + 1, k)
3. 利用itertools.combinations
T: k * C(k, n) => k * n! / k! / (n - k)!
S: k * C(k, n) => k * n! / k! / (n - k)!
Code:
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: nums = [i for i in range(1, n + 1)] return itertools.combinations(nums, k)