77. 组合
求组合,注意终止条件。
class Solution {List<List<Integer> > res = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> combine(int n, int k) {combine(n,k,1);return res;}void combine(int n,int k,int index){if(path.size() == k) {// 这儿一定要返回的是new ArrayList<>(path)res.add(new ArrayList<>(path));return;}for(int i = index;i<=n-(k-path.size())+1;i++){path.add(i);combine(n,k,i+1);// 要用removeLast的前提是path需要定义为LinkedListpath.removeLast();}}}
216. 组合总和 III
没有剪枝的时候,提交超时了。进行了剪枝才可以。
class Solution {List<List<Integer>> res = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum3(int k, int n) {backtracking(k,n,1,0);return res;}void backtracking(int k,int n,int startIndex,int sum){if(path.size()==k){if(sum==n){res.add(new ArrayList<>(path));}return;}for(int i = startIndex;i<=9-(k-path.size())+1;i++){path.add(i);sum+=i;backtracking(k,n,i+1,sum);path.removeLast();sum-=i;}}}
二刷的时候我没剪枝,然后也过了。
class Solution {List<List<Integer>> res = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum3(int k, int n) {combinationSum3(n,k,1);return res;}void combinationSum3(int n,int k,int index){// 终止条件 path.size() == k , n == 0if(path.size() == k){if(n == 0){res.add(new ArrayList<>(path));return;}}// 单层逻辑处理for(int i = index;i<=9;i++){path.add(i);combinationSum3(n-i,k,i+1);// 回溯处理path.removeLast();}}}
17. 电话号码的字母组合(抄)
class Solution {// 设置全局链表来存储最后的结果List<String> list = new ArrayList<>();public List<String> letterCombinations(String digits) {if(digits==null||digits.length()==0){return list;}// 初始对应所有的数字,为了直接对应2-9,新增了两个无效的字符串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);}}}
