我新建的个人博客,欢迎访问: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; } String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; backTracking(digits, numString, 0); return list;
}
StringBuilder temp = new StringBuilder();
public void backTracking(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)); backTracking(digits, numString, num + 1); temp.deleteCharAt(temp.length() - 1); } } }
|