77. 组合
https://leetcode.cn/problems/combinations/description/
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return res;
}
public void backtracking(int n, int k,int start){
if (path.size() == k){
res.add(new ArrayList<>(path));
return;
}
for (int i = start;i <= n ;i++){
path.add(i);
backtracking(n,k,i+1);
path.remove(path.size() - 1);
}
}
总结:回溯,每次选一个点,for中是这一横层的选点,选完了把下一个点放进去,放完了拿出来。
216. 组合总和 III
https://leetcode.cn/problems/combinations/description/
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> combinationSum3(int k, int n) {
res = new ArrayList<>();
path = new ArrayList<>();
backtracking(k,n,1);
return res;
}
public void backtracking(int k,int n,int start){
if (path.size() > k) return;//这句话就是剪枝优化
if (path.size() == k){
int count = 0;
for (Integer integer : path) {
count += integer;
}
if (count == n){
res.add(new ArrayList<>(path));
return;
}else {
return;
}
}
for (int i = start; i <= 9; i++) {
path.add(i);
backtracking(k,n,i+1);
path.remove(path.size() - 1);
}
}
总结:回溯,每次长度够了就看值是否符合,长度超了就直接return
17. 电话号码的字母组合
https://leetcode.cn/problems/letter-combinations-of-a-phone-number/description/
List<String> res;
StringBuilder path;
HashMap<Integer,String> map;
int digitsLen;
public List<String> letterCombinations(String digits) {
res = new ArrayList<>();
path = new StringBuilder();
map = new HashMap<>();
if (digits.isEmpty()) return res;
map.put(2,"abc");
map.put(3,"def");
map.put(4,"ghi");
map.put(5,"jkl");
map.put(6,"mno");
map.put(7,"pqrs");
map.put(8,"tuv");
map.put(9,"wxyz");
digitsLen = digits.length();
backtracking(0,digits);
return res;
}
public void backtracking(int num,String digits){
if (path.length() == digitsLen){
res.add(path.toString());
return;
}
int key = digits.charAt(num) - '0';
String str = map.get(key);
for (int i = 0; i < str.length(); i++) {
path.append(str.charAt(i));
backtracking(num+1,digits);
path.deleteCharAt(path.length()-1);
}
}
总结:用回溯,先把每个数字和对应的字符串存到map中,再去遍历字符串的每个位置的数字,取出对应的str,把str进行回溯。
标签:map,return,组合,int,res,随想录,new,字母组合,path From: https://www.cnblogs.com/jeasonGo/p/18115699