今天是第二十五天,回溯算法
class Solution { List<List<Integer>> res = new ArrayList<>(); List<Integer> paths = new ArrayList<>(); int sum = 0; public List<List<Integer>> combinationSum3(int k, int n) { backtrack(k, n, 1); return res; } public void backtrack(int k, int n, int startIndex){ if(sum>n || paths.size()+n - startIndex + 1 < k){ return; } if(sum == n && paths.size() == k){ res.add(new ArrayList<>(paths)); return; } for(int i = startIndex; i <= n && i <= 9; i++){ paths.add(i); sum += i; backtrack(k, n, i + 1); sum -= i; paths.remove(paths.size() - 1); } } }
很典型的回溯算法题,求1-9相加为n的k个个数组合
class Solution { String[] mappings = new String[]{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; List<String> res = new ArrayList<>(); public List<String> letterCombinations(String digits) { if (digits == "" || digits.length() == 0) { return res; } func(new StringBuilder(), digits, 0); return res; } private void func(StringBuilder sb, String digits, int index) { if (sb.length() == digits.length()) { res.add(sb.toString()); return; } Integer num = Integer.valueOf(String.valueOf(digits.charAt(index))); for (int i = 0; i < mappings[num].length(); i++) { sb.append(mappings[num].charAt(i)); func(sb, digits, index + 1); sb.deleteCharAt(index); } } }
没想出来完全
回溯算法这块还是不是很理解 得练
标签:digits,sb,return,int,res,随想录,回溯,new,第二十五 From: https://www.cnblogs.com/catSoda/p/16862374.html