这道题目需要找出所有由k个数相加得到n的组合,其中每个数都在1-9之间且不重复。解决这道题目可以采用回溯算法,具体思路如下:
定义一个backtrack函数,其中传入的参数有当前的组合candidates、当前的和sum、当前已选的数字个数count、需要选的数字个数k、需要得到的和n、以及结果集res。
在backtrack函数中,首先判断当前的数字个数是否等于k,如果是,再判断当前的和是否等于n,如果是,则将当前candidates加入结果集res中。
然后从1到9中遍历,如果当前数字不在candidates中且当前数字加上当前和不大于n,则将当前数字加入candidates中,并且递归调用backtrack函数。
递归调用结束后,将当前数字从candidates中移除,继续遍历下一个数字。
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> candidates = new ArrayList<>();
backtrack(candidates, 0, 0, k, n, res);
return res;
}
public void backtrack(List<Integer> candidates, int sum, int count, int k, int n, List<List<Integer>> res) {
if (count == k) {
if (sum == n) {
res.add(new ArrayList<>(candidates));
}
return;
}
for (int i = 1; i <= 9; i++) {
if (!candidates.contains(i) && sum + i <= n) {
candidates.add(i);
backtrack(candidates, sum + i, count + 1, k, n, res);
candidates.remove(candidates.size() - 1);
}
}
}
}
这道题目需要找出所有由给定电话号码中的数字组成的字母组合。解决这道题目可以采用回溯算法,具体思路如下:
定义一个backtrack函数,其中传入的参数有当前的组合combination、当前组合的长度len、需要得到的组合长度digits、电话号码digits_map以及结果集res。
在backtrack函数中,首先判断当前的组合长度是否等于需要得到的组合长度,如果是,则将当前组合加入结果集res中。
然后从digits_map中找到当前数字对应的字母字符串,遍历其中的字符,将每个字符加入combination中,并且递归调用backtrack函数。
递归调用结束后,将combination中最后一个字符移除,继续遍历下一个字符。
class Solution {
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return res;
}
Map<Character, String> digits_map = new HashMap<>();
digits_map.put('2', "abc");
digits_map.put('3', "def");
digits_map.put('4', "ghi");
digits_map.put('5', "jkl");
digits_map.put('6', "mno");
digits_map.put('7', "pqrs");
digits_map.put('8', "tuv");
digits_map.put('9', "wxyz");
backtrack(new StringBuilder(), 0, digits.length(), digits, digits_map, res);
return res;
}
public void backtrack(StringBuilder combination, int len, int digits_len, String digits, Map<Character, String> digits_map, List<String> res) {
if (len == digits_len) {
res.add(combination.toString());
return;
}
String letters = digits_map.get(digits.charAt(len));
for (int i = 0; i < letters.length(); i++) {
combination.append(letters.charAt(i));
backtrack(combination, len + 1, digits_len, digits, digits_map, res);
combination.deleteCharAt(combination.length() - 1);
}
}
}