赞
踩
画出来的树是这样
记录所有组合,一个变量current装当前的处理结果,一个res装所有的处理的结果
回溯三部曲:
下面的代码还可以剪枝优化
class Solution { List<List<Integer>> res; List<Integer> curent; public List<List<Integer>> combine(int n, int k) { res = new LinkedList<>(); curent = new LinkedList<>(); backtracing(n, k, 1); return res; } void backtracing(int n, int k, int startIndex) { if (curent.size() == k) { LinkedList<Integer> temp = new LinkedList<>(curent); res.add(temp); } for (int i = startIndex; i < n+1; i++) { curent.add(i); backtracing(n, k, i + 1); curent.remove(curent.size() - 1); } } }
画出抽象的树
这一题和上一题的最大区别在于终止条件有点不一样
记录所有组合,一个变量current装当前的处理结果,一个res装所有的处理的结果
回溯三部曲
还是一样,可以剪枝优化
class Solution { List<List<Integer>> res; List<Integer> current; int target; public List<List<Integer>> combinationSum3(int k, int n) { res = new LinkedList<>(); current = new LinkedList<>(); target = n; backtracing(k, 1); return res; } void backtracing(int k, int startIndex) { if (current.size() == k) { if (getListSum(current) == target) { List<Integer> temp = new LinkedList<>(current); res.add(temp); return; } else { return; } } for (int i = startIndex; i < 10; i++) { current.add(i); backtracing(k, i + 1); current.remove(current.size() - 1); } } int getListSum(List<Integer> list) { int sum = 0; for (int i = 0; i < list.size(); i++) { sum += list.get(i); } return sum; } }
这道题我感觉区别就在于每次for循环遍历的东西是动态变化的,因此需要再入参的地方传入
准备工作:准备一个二维列表,大小为8,存储2-9所代表的字母。
List<List<Integer>> store = Arrays.asList(
Arrays.asList("a", "b", "c"),
Arrays.asList("d", "e", "f"),
Arrays.asList("g", "h", "i"),
Arrays.asList("j", "k", "l"),
Arrays.asList("m", "n", "o"),
Arrays.asList("p", "q", "r","s"),
Arrays.asList("t", "u", "v"),
Arrays.asList("w", "x", "y","z"),
);
记录所有组合,一个变量current装当前的处理结果,一个res装所有的处理的结果
回溯三部曲
class Solution { List<List<String>> store; char[] digitsArr; StringBuilder current; List<String> res; public List<String> letterCombinations(String digits) { store = Arrays.asList( Arrays.asList("a", "b", "c"), Arrays.asList("d", "e", "f"), Arrays.asList("g", "h", "i"), Arrays.asList("j", "k", "l"), Arrays.asList("m", "n", "o"), Arrays.asList("p", "q", "r", "s"), Arrays.asList("t", "u", "v"), Arrays.asList("w", "x", "y", "z") ); digitsArr = digits.toCharArray(); current = new StringBuilder(); res = new LinkedList<>(); if (digits.equals("")) return res; bk(0); return res; } void bk(int index) { if (current.length() == digitsArr.length) { String temp = current.toString(); res.add(temp); return; } int number = Integer.parseInt(String.valueOf(digitsArr[index])); List<String> listForSearch = store.get(number - 2); for (int i = 0; i < listForSearch .size(); i++) { current.append(listForSearch .get(i)); bk(index + 1); current.deleteCharAt(current.length() - 1); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。