力扣216:组合总和|||
题目链接:力扣216:组合总和|||
思路:
1.因为是暴力搜索,所以采用回溯算法,并定义两个变量result(List<List< Integer>>)和path(List< Integer>),注:关于回溯算法一定要先画树状图理解
2.确定递归参数(int n, int k, int startIndex, int sum)
3.确定递归终止条件(当path大小==k) ,如果sum == n则添加到result中
4.确定每层递归逻辑(添加元素,深度递归遍历,撤销最后一个元素)
代码:
class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
// 1.确认参数
backTracking(k, n, 1, 0);
return result;
}
public void backTracking(int k, int n, int startIndex, int sum) {
// 2.确定终止条件
if (path.size() == k) {
if (sum == n) {
result.add(new ArrayList<>(path));
}
return;
}
// 3.处理单层逻辑
for (int i = startIndex; i <= 9; i++) {
sum += i;
path.add(i);
backTracking(k, n, i+1, sum);
sum -= i;
path.removeLast();
}
}
}
力扣17:电话号码的字母组合
题目链接:力扣17:电话号码的字母组合
思路:
1.因为是暴力搜索,所以采用回溯算法,并定义两个变量result(List<List< Integer>>)和path(List< Integer>),注:关于回溯算法一定要先画树状图理解
2.建立手机键盘数字与字母的映射数组
3.确定递归参数(String digits, String[] numString, int num)
4.确定递归终止条件(当digits.length() == num)
5.确定每层递归逻辑(添加元素,深度递归遍历,撤销最后一个元素)
代码:
class Solution {
// 设置全局结果集
List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return result;
}
// 1.初始化数组,使之数字与字母集对应
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
// 2.确定参数
backTracking(digits, numString, 0);
return result;
}
StringBuilder temp = new StringBuilder();
public void backTracking(String digits, String[] numString, int num) {
// 3.确定终止条件
if (digits.length() == num) {
result.add(temp.toString());
return;
}
// 4.处理单层逻辑
//str 表示当前num对应的字符串
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
backTracking(digits, numString, num + 1);
temp.deleteCharAt(temp.length() - 1);
}
}
}