77. 组合
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
class Solution {
public List<List<Integer>> res = new ArrayList<>();
public List<Integer> path = new LinkedList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n ,k ,1);
return res;
}
public void backtracking(int n, int k, int index){
if(path.size() == k){
res.add(new LinkedList<>(path));
return;
}
for(int i = index; i <= n; i++){
path.add(i);
backtracking(n, k, i+1);
path.removeLast();
}
}
}
216.组合总和III
找出所有相加之和为 n
的 k
个数的组合,且满足下列条件:
- 只使用数字1到9
- 每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入: k = 3, n = 7 输出: [[1,2,4]] 解释: 1 + 2 + 4 = 7 没有其他符合的组合了。
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(k, n, 1, 0);
return res;
}
public void backtracking(int k, int n, int index, int sum){
if(path.size() == k){
if(sum == n) res.add(new LinkedList(path));
return;
}
for(int i = index; i <= 9; i++){
path.add(i);
sum += i;
backtracking(k, n, i+1, sum);
sum -= i;
path.removeLast();
}
}
}
17.电话号码的字母组合
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"
class Solution {
List<String> res = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits.length() == 0) return res;
String[] arr = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
backtracking(digits, arr, 0);
return res;
}
StringBuilder sb = new StringBuilder();
public void backtracking(String digits, String[] arr, int index){
if(index == digits.length()){
res.add(sb.toString());
return;
}
String str = arr[digits.charAt(index) - '0'];
for(int i = 0; i < str.length(); i++){
sb.append(str.charAt(i));
backtracking(digits, arr, index+1);
sb.deleteCharAt(sb.length() - 1);
}
}
}