一、77. 组合
题目链接:https://leetcode.cn/problems/combinations/
文章讲解:https://programmercarl.com/0077.%E7%BB%84%E5%90%88.html
视频讲解:https://www.bilibili.com/video/BV1ti4y1L7cv
1.1 初见思路
- 组合问题用回溯
- 学会使用剪枝
1.2 具体实现
class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> cur = new ArrayList<>();public List<List<Integer>> combine(int n, int k) {backTrack(n,1,k);return res;}public void backTrack(int n,int startIndex,int k){if(cur.size()==k){res.add(new ArrayList<>(cur));return;}for(int i=startIndex;i <= n - (k - cur.size()) + 1;i++){cur.add(i);backTrack(n,i+1,k);cur.removeLast();}}
}
1.3 重难点
二、 216.组合总和III
题目链接:https://leetcode.cn/problems/combination-sum-iii/
文章讲解:https://programmercarl.com/0216.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CIII.html
视频讲解:https://www.bilibili.com/video/BV1wg411873x
2.1 初见思路
2.2 具体实现
class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> combinationSum3(int k, int n) {backtracking(k, n, 1, 0);return res;}public void backtracking(int k, int n, int startIndex, int sum) {if (sum > n) {return;}if (path.size() == k) {if (sum == n) {res.add(new ArrayList<>(path));return;}}for (int i = startIndex; i <= 9; i++) {path.add(i);sum += i;backtracking(k, n, i + 1, sum);path.removeLast();sum -= i;}}
}
2.3 重难点
三、 17.电话号码的字母组合
题目链接:https://leetcode.cn/problems/letter-combinations-of-a-phone-number/
文章讲解:https://programmercarl.com/0017.%E7%94%B5%E8%AF%9D%E5%8F%B7%E7%A0%81%E7%9A%84%E5%AD%97%E6%AF%8D%E7%BB%84%E5%90%88.html
视频讲解:https://www.bilibili.com/video/BV1yV4y1V7Ug
3.1 初见思路
- 数字和字母之间的对应关系,可以用map,也可以用数组表示,这种个位数个元素的情况都可以采用数组的形式来实现
- 组合题目用回溯来实现,回溯三部曲:返回值+入参,终止条件,单层循环逻辑
3.2 具体实现
class Solution {List<String> res = new ArrayList<>();StringBuilder temp = new StringBuilder();String[] numArr = {"","","abc","def","ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};public List<String> letterCombinations(String digits) {if(digits==null || digits=="" || digits.length()==0){return res;}backtracking(digits,0);return res;}public void backtracking(String digits,int index){if(index==digits.length()){res.add(temp.toString());return ;}String tempStr = numArr[digits.charAt(index)-'0'];for(int i=0;i<tempStr.length();i++){temp.append(tempStr.charAt(i));backtracking(digits,index+1);temp.deleteCharAt(temp.length() - 1);}}
}
3.3 重难点
- 下标index表示的含义是取digits的数字的下标,拿到对应数字后再拿对应的字母字符串;存在一次转换,要注意转换