1. Combination Sum III (Leetcode Number: 669)
a. WITHOUT OPTIMIZATION: Compared with problem 77, the condition to stop the recursion needs to be revised as the given numbers are clearly declared and sit between 1 to 9.
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
sub_res = []
def backtracking(n, k, st_id):
if sum(sub_res) == n and len(sub_res) == k:
res.append(sub_res[:])
return
for i in range(st_id, 10):
sub_res.append(i)
backtracking(n, k, i + 1)
sub_res.pop()
backtracking(n, k, 1)
return res
b. WITH OPTIMIZATION: If the sum of sub_res is bigger than n, the current recursion could be skipped.
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res = []
sub_res = []
def backtracking(n, k, st_id):
if sum(sub_res) == n and len(sub_res) == k:
res.append(sub_res[:])
return
if sum(sub_res) > n:
return
for i in range(st_id, 10):
sub_res.append(i)
backtracking(n, k, i + 1)
sub_res.pop()
backtracking(n, k, 1)
return res
2. Letter Combinations of a Phone Number (Leetcode Number: 669)
In this case dictionary is used as the input number has been mapped to a few letters. The inputs of backtracking function here are the index of the original input string digits and a string of potential combinations.
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
res = []
digits_li = list(digits)
if len(digits) == 0:
return []
num_map = {
'2' : 'abc',
'3' : 'def',
'4' : 'ghi',
'5' : 'jkl',
'6' : 'mno',
'7' : 'pqrs',
'8' : 'tuv',
'9' : 'wxyz'
}
def backtracking(i, sub_res):
if len(sub_res) == len(digits):
res.append(''.join(sub_res))
return
letter_list = num_map[digits[i]]
for letter in letter_list:
sub_res.append(letter)
backtracking(i + 1, sub_res)
sub_res.pop()
backtracking(0, [])
return res