216. 组合总和 III
1. first idea
I set the root as .
Then, the branches are from to . For each traversal, the input parameter is a temporal list which stores the number using for subtraction.
As the children for the branch , the branches are from to .
If any leaves are zeros, their temporal lists are the results.
class Solution:
def __init__(self):
self.res_list = []
def bfs(self, tmp_list, k, n, tmp_sum):
if k == len(tmp_list):
if tmp_sum == n:
self.res_list.append(tmp_list)
return
else:
start_idx = tmp_list[-1] + 1 if tmp_list else 1
for i in range(start_idx, min(n - tmp_sum, 9) + 1):
self.bfs(tmp_list + [i], k, n, tmp_sum + i)
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
self.bfs([], k, n, 0)
return self.res_list
Practically, I store the temporal sum value in each node instead of .
2. learning time
30min.
17. 电话号码的字母组合
1. first idea
class Solution:
def __init__(self):
self.res_list = []
self.char_dict = {
"2": ["a", "b", "c"],
"3": ["d", "e", "f"],
"4": ["g", "h", "i"],
"5": ["j", "k", "l"],
"6": ["m", "n", "o"],
"7": ["p", "q", "r", "s"],
"8": ["t", "u", "v"],
"9": ["w", "x", "y", "z"]
}
def dfs(self, tmp_list, left_chars_list):
if len(left_chars_list) == 0:
self.res_list.append("".join(tmp_list))
return
else:
ch_list = self.char_dict[left_chars_list[0]]
for ch in ch_list:
self.dfs(tmp_list + [ch], left_chars_list[1:])
def letterCombinations(self, digits: str) -> List[str]:
digits_list = list(digits)
self.dfs([], digits_list)
if self.res_list == [""]:
return []
return self.res_list
It is easy.
2. learning time
30min.