xxx1和xxx2一般是题目所给的值
startIndex用于for循环的开始
void getResult(xxx1,xxx2,startIndex){
if(满足了条件){
xxxx;
return;
}
for(int i = startIndex;i< ?;i++){
//处理结点
getResult(xxx1,xxx2,startIndex);
//回溯
}
}
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
class Solution {
Deque<Integer> path = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
getResult(n,k,1);
return result;
}
public void getResult(int n,int k,int startIndex){
if(path.size() == k){
result.add(new ArrayList(path));
return;
}
for(int i = startIndex;i<=n;i++){
path.add(i);
getResult(n,k,i+1);
path.removeLast();
}
}
}
找出所有相加之和为 n
的 k
个数的组合,且满足下列条件:
- 只使用数字1到9
- 每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入: k = 3, n = 7 输出: [[1,2,4]] 解释: 1 + 2 + 4 = 7 没有其他符合的组合了。
示例 2:
输入: k = 3, n = 9 输出: [[1,2,6], [1,3,5], [2,3,4]] 解释: 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 没有其他符合的组合了。
示例 3:
输入: k = 4, n = 1 输出: [] 解释: 不存在有效的组合。 在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。
class Solution {
Deque<Integer> path = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
int sum = 0;
public List<List<Integer>> combinationSum3(int k, int n) {
getResult(k,n,1);
return result;
}
public void getResult(int k,int n,int startIndex){
if(sum > n){
return;
}
if(path.size() == k && sum == n ){
result.add(new ArrayList(path));
return;
}
for(int i =startIndex;i<=9;i++){
path.add(i);
sum+=i;
getResult(k,n,i+1);
path.removeLast();
sum-=i;
}
}
}
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = "23" 输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]
示例 2:
输入:digits = "" 输出:[]
示例 3:
输入:digits = "2" 输出:["a","b","c"]
class Solution {
String[] num = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
StringBuilder sb = new StringBuilder();;
List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if(digits.length() ==0){
return result;
}
getResult(digits,0);
return result;
}
public void getResult(String digits,int digitsIndex){
if(sb.length() == digits.length()){
result.add(sb.toString());
return;
}
String numStr = num[digits.charAt(digitsIndex)-'0'];
for(int i =0;i<numStr.length();i++){
sb.append(numStr.charAt(i));
getResult(digits,digitsIndex+1);
sb.deleteCharAt(sb.length()-1);
}
}
}