1、
A combinatorial problem like this one can only be solved using the exhaustive method, however, for the exhaustive problem, we can use backtracking.
1)Determining Recursive Function Arguments
One-dimensional array path to hold the results that match the condition, and two-dimensional array result to hold the result set
- targetSum(int)目标和,也就是题目中的n。
- k(int)就是题目中要求k个数的集合。
- sum(int)为已经收集的元素的总和,也就是path里元素的总和。
- startIndex(int)为下一层for循环搜索的起始位置。
vector<vector<int>> result;
vector<int> path;
void backtracking(int targetSum, int k, int sum, int startIndex)
2)Determination of termination conditions
if (path.size() == k) {
if (sum == targetSum) result.push_back(path);
return; // 如果path.size() == k 但sum != targetSum 直接返回
}
3)single-level search process
本题和77. 组合 (opens new window)区别之一就是集合固定的就是9个数[1,...,9],所以for循环固定i<=9
for (int i = startIndex; i <= 9; i++) {
sum += i;
path.push_back(i);
backtracking(targetSum, k, sum, i + 1); // 注意i+1调整startIndex
sum -= i; // 回溯
path.pop_back(); // 回溯
}
//别忘了处理过程 和 回溯过程是一一对应的,处理有加,回溯就要有减!
class Solution(object):
def combinationSum3(self, k, n):
"""
:type k: int
:type n: int
:rtype: List[List[int]]
"""
#self.vec result
#self.vec path
# 这里可以用[]
#result.clear(); // 可以不加
#path.clear(); // 可以不加
result = []
#要➕self
self.backtracking(n, k, 0, 1, [], result)
return result
def backtracking(self, targetSum, k, sum, startIndex,path, result): # 注意这里要把path和result加进来,其他语言是因为定义了全局变量,所以不用加,但是这里我们没有定义全局变量
if sum > targetSum:
return
if len(path) == k:
if sum == targetSum:
result.append(path[:]) #why? vs path[] reference
# Shallow Copy
# when you want to create a copy of a list
return
for i in range(startIndex,9 - (k - len(path)) + 2):
sum = sum + i
#path.push(i)
path.append(i)
self.backtracking(targetSum, k, sum, i+1,path, result)
sum = sum - i
path.pop()
2、
17. Letter Combinations of a Phone Number
理解本题后,要解决如下三个问题:
- 数字和字母如何映射
- 两个字母就两个for循环,三个字符我就三个for循环,以此类推,然后发现代码根本写不出来
- 输入1 * #按键等等异常情况
1)如何映射How to map
You can use a map or define a two-dimensional array.
const string letterMap[10] = {
"", // 0
"", // 1
"abc", // 2
"def", // 3
"ghi", // 4
"jkl", // 5
"mno", // 6
"pqrs", // 7
"tuv", // 8
"wxyz", // 9
};
2)backtracking
Horizontal
Vertical
A. Determining Recursive Function Arguments
path, result, string digital, index
vector<string> result;
string s;
void backtracking(const string& digits, int index)
B. Determination of termination conditions
same
if (index == digits.size()) {
result.push_back(s);
return;
}
C. Single-level search process
首先要取index指向的数字,并找到对应的字符集(手机键盘的字符集)。
int digit = digits[index] - '0'; // 将index指向的数字转为int
string letters = letterMap[digit]; // 取数字对应的字符集
for (int i = 0; i < letters.size(); i++) {
s.push_back(letters[i]); // 处理
backtracking(digits, index + 1); // 递归,注意index+1,一下层要处理下一个数字了
s.pop_back(); // 回溯
}
class Solution(object):
def __init__(self):
self.letterMap = [
"", #0
"", #1
"abc", #2
"def", #3
"ghi", #4
"jkl", #5
"mno", #6
"pqrs", #7
"tuv", #8
"wxyz", #9
]
self.result = []
self.path = ""
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if len(digits) == 0:
return self.result
self.backtracking(digits, 0)
return self.result
def backtracking(self, digits, index):
if index == len(digits):
self.result.append(self.path)
return
digit = int(digits[index])
# transfer the index from string to int
letters = self.letterMap[digit]
# get the map set of letters
for i in range(len(letters)):
self.path += letters[i]
self.backtracking(digits, index + 1)
self.path = self.path[:-1]
#backtrack, delete the last add letter
#self.path.pop()
# 不能用pop,因为path我们定义是为“”字符串类型?