我新建的个人博客,欢迎访问:hmilzy.github.io


216.组合总和III

题目链接: 组合总和III

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

class Solution {

List<Integer> path = new ArrayList<>();
List<List<Integer>> result = new ArrayList<>();

public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(n,0,k,1);
return result;
}

public void backtracking(int targetSum,int sum,int k,int startIndex) {
if(sum > targetSum){
return ;
}

if(path.size() == k) {
if(sum == targetSum){
result.add(new ArrayList<>(path));
return ;
}
}

for(int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
path.add(i);
sum += i;
backtracking(targetSum,sum,k,i + 1);
path.remove(path.size() - 1);
sum -= i;
}
}
}


17.电话号码的字母组合

题目链接: 电话号码的字母组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

class Solution {

//设置全局列表存储最后的结果
List<String> list = new ArrayList<>();

public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return list;
}
//初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串""
String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
//迭代处理
backTracking(digits, numString, 0);
return list;

}

//每次迭代获取一个字符串,所以会设计大量的字符串拼接,所以这里选择更为高效的 StringBuild
StringBuilder temp = new StringBuilder();

//比如digits如果为"23",num 为0,则str表示2对应的 abc
public void backTracking(String digits, String[] numString, int num) {
//遍历全部一次记录一次得到的字符串
if (num == digits.length()) {
list.add(temp.toString());
return;
}
//str 表示当前num对应的字符串
String str = numString[digits.charAt(num) - '0'];
for (int i = 0; i < str.length(); i++) {
temp.append(str.charAt(i));
//c
backTracking(digits, numString, num + 1);
//剔除末尾的继续尝试
temp.deleteCharAt(temp.length() - 1);
}
}
}