題目出處
難度
medium
個人範例程式碼
from typing import (
List,
)
class Solution:
"""
@param a: an integer array
@param k: a postive integer <= length(A)
@param target: an integer
@return: A list of lists of integer
we will sort your return value in output
"""
def k_sum_i_i(self, a: List[int], k: int, target: int) -> List[List[int]]:
# write your code here
if not a:
return []
self.ans = []
self.dfs(a, k, target, [], 0)
return self.ans
def dfs(self, a, k, target, path, start_idx):
# end of recursion
if k <= 0:
if sum(path) == target:
self.ans.append(list(path)) # deepcopy
return
# define and split
for idx in range(start_idx, len(a)):
path.append(a[idx])
self.dfs(a, k-1, target, path, idx+1)
path.pop() # backtracking
算法說明
- 此題有類似問題,差別是在這題是「限制可用數字的數量」,可參考:
https://wongwongnotes-github-io.pages.dev/python/leetcode-python-39/
https://wongwongnotes-github-io.pages.dev/python/leetcode-python-40/
組合類的問題,使用 dfs 搜尋出全部的組合,在判斷可行的方案。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解
input handling
如果沒有 a,直接 return []
Boundary conditions
見上述說明