代码随想录训练营第25天|216.组合总和III,17.电话号码的字母组合
)
216.组合总和III
文章
思路
給定了[1, 10)区间,从小到大向组合中添数,每次向下一层需要令 k 减1,令n减当前数,到 k 为 0 且 n为 0 时可以向结果中添加组合并返回
剪枝的话就是判断当前值向后连续k个累加会不会大于n,如果大于则说明该分支没有回溯的价值于是剪枝,我下面代码图省事没有求累加而是算 k * start
代码
class Solution {
private List<Integer> combination;
private List<List<Integer>> combinations;
public List<List<Integer>> combinationSum3(int k, int n) {
combination = new ArrayList<>();
combinations = new ArrayList<>();
dfs(1, 10, k, n);
return combinations;
}
public void dfs(int start, int end, int k, int n) {
if (k == 0 && n == 0) {
combinations.add(new ArrayList<>(combination));
return;
} else if (!(k * start <= n && n >= start)) {
return;
}
int i;
for (i = start; i < end; ++i) {
combination.add(i);
dfs(i + 1, end, k - 1, n - i);
combination.remove(combination.size() - 1);
}
}
}
17.电话号码的字母组合
文章
思路
提前建立好从数字到字符集合的映射,探索到字符串尽头时增加结果并返回,同一层则按顺序依次dfs
代码
class Solution {
private char[][] map = {
{'a', 'b', 'c'},
{'d', 'e', 'f'},
{'g', 'h', 'i'},
{'j', 'k', 'l'},
{'m', 'n', 'o'},
{'p', 'q', 'r', 's'},
{'t', 'u', 'v'},
{'w', 'x', 'y' ,'z'}
};
private StringBuffer sb;
private List<String> results;
public List<String> letterCombinations(String digits) {
sb = new StringBuffer();
results = new ArrayList<>();
dfs(digits, 0);
return results;
}
public void dfs(String digits, int start) {
if (start == digits.length()) {
if (sb.length() > 0)
results.add(sb.toString());
return;
}
char cur = digits.charAt(start);
char[] cur_nums = map[cur - '2'];
int i;
for (i = 0; i < cur_nums.length; ++i) {
sb.append(cur_nums[i]);
dfs(digits, start + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
总结
依旧是边界难处理,昨晚提前看了,今天做题也还是要一个小时,但是没时间了今天