216.组合总和III
题目
文章讲解
视频讲解
思路:
以回溯函数做对称,上面做了什么操作,下面也是
class Solution {List<List<Integer>> result = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum3(int k, int n) {travelsal(k, n, 1, 0);return result;}private void travelsal(int k, int n, int startIndex, int sum) {if (sum == n && path.size() == k) {result.add(new ArrayList<>(path));return;}for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {if (sum > n || path.size() > k)break;path.add(i);sum += i;travelsal(k, n, i + 1, sum);sum -= i;path.removeLast();}}
}
17.电话号码的字母组合
题目
文章讲解
视频讲解
思路:思路上和组合很像,不同的是对字符串进行操作
class Solution {List<String> list = new ArrayList<>();public List<String> letterCombinations(String digits) {if (digits == null || digits.length() == 0)return list;String[] numString = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };travelsal(digits, numString, 0);return list;}StringBuilder temp = new StringBuilder();public void travelsal(String digits, String[] numString, int num) {if (num == digits.length()) {list.add(temp.toString());return;}String str = numString[digits.charAt(num) - '0'];for (int i = 0; i < str.length(); i++) {temp.append(str.charAt(i));travelsal(digits, numString, num + 1);temp.deleteCharAt(temp.length() - 1);}}
}
还得再想想