LeetCode 216. 组合总和 III
题目链接:216. 组合总和 III - 力扣(LeetCode)
思路:
这道题的要求返回的组合不能有相同的,那么我们递归的每一次过程中,用一个for循环来遍历所有满足条件的放入临时数组path中,判断条件是:如果加数的个数正确了,和也等于目标数,就把当前内容添加一份至res。剪枝的过程就是没必要所有都判断。剩余加的数小了可以递归,否则break进入下一轮。
代码:
#python
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res, path = [], []
if k == 0:
return res
def dfs(i):
if sum(path) == n and len(path) == k:
res.append(path.copy())
return
diff = n - sum(path)
for j in range(i, 10):
if j <= diff:
path.append(j)
dfs(j + 1)
path.pop()
dfs(1)
return res
/java
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
traversal(1, n, k, res, path);
return res;
}
private static void traversal(int cur_idx, int n, int k, List<List<Integer>> res, List<Integer> path){
if(path.size() == k){
int sum = 0;
for(int i : path){
sum += i;
}
if(sum == n){
res.add(new ArrayList<>(path));
}
return;
}
if(n - cur_idx + 1 < k - path.size()){
return;
}
for(int j = cur_idx; j <= 9; j++){
path.add(j);
traversal(j + 1, n, k, res, path);
path.remove(path.size() - 1);
}
}
}
LeetCode 17. 电话号码的字母组合
题目链接:17. 电话号码的字母组合 - 力扣(LeetCode)
思路:
重点是如何将每个数字按键与字母所对应起来,其实可以发现,键盘的数字和单个位置的数字相同,因此我们可以考虑用一个数组来存储键盘的字母,用其下标来表示号码的数字,在每一次遍历的时候,使用for循环遍历数组该位置的所有字母,并且添加至path中进行下一轮递归。边界中止条件是当输入的数字长度与临时数组的长度相等时。
代码:
#python
match = ['', '','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if digits == "":
return []
digits = list(map(int, digits))
res, path = [], []
def dfs(i):
if len(digits) == len(path):
res.append(''.join(path))
return
for x in match[digits[i]]:
path.append(x)
dfs(i + 1)
path.pop()
dfs(0)
return res
/java
class Solution {
public List<String> letterCombinations(String digits) {
if(digits.equals("")){
return new ArrayList<>();
}
char[] words = digits.toCharArray();
List<String> res = new ArrayList<>();
Deque<Character> path = new ArrayDeque<>();
Map<Character, List<Character>> map = new HashMap<>();
map.put('2', Arrays.asList('a', 'b', 'c'));
map.put('3', Arrays.asList('d', 'e', 'f'));
map.put('4', Arrays.asList('g', 'h', 'i'));
map.put('5', Arrays.asList('j', 'k', 'l'));
map.put('6', Arrays.asList('m', 'n', 'o'));
map.put('7', Arrays.asList('p', 'q', 'r', 's'));
map.put('8', Arrays.asList('t', 'u', 'v'));
map.put('9', Arrays.asList('w', 'x', 'y', 'z'));
traversal(0, words, res, path, map);
return res;
}
private static void traversal(int cur_idx, char[] words, List<String> res, Deque<Character> path, Map<Character, List<Character>> map){
if(cur_idx == words.length){
StringBuilder sb = new StringBuilder();
for(char ch : path){
sb.append(ch);
}
res.add(sb.toString());
return;
}
for(char ch : map.get(words[cur_idx])){
path.offerLast(ch);
traversal(cur_idx + 1, words, res, path, map);
path.pollLast();
}
}
}