[TOC]

回溯算法

本质还是暴力搜索,但是可以利用剪枝进行优化

77. Combinations

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.

Example 2:

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

Constraints:

  • 1 <= n <= 20
  • 1 <= k <= n

正常回溯

class Solution {


public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> resultList = new ArrayList<>();
Deque<Integer> queue = new ArrayDeque<>();
backtracing(n,k,1,resultList,queue);
return resultList;
}
public void backtracing(int n,int k,int cur,List<List<Integer>> resultList,Deque<Integer> queue){
if(queue.size()==k){
resultList.add(new ArrayList(queue));
return ;
}
for(int i = cur;i<=n;i++){
queue.add(i);
backtracing(n,k,i+1,resultList,queue);
queue.removeLast();
}
}

}

剪枝优化

class Solution {


public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> resultList = new ArrayList<>();
Deque<Integer> queue = new ArrayDeque<>();
backtracing(n,k,1,resultList,queue);
return resultList;
}
public void backtracing(int n,int k,int cur,List<List<Integer>> resultList,Deque<Integer> queue){
if(queue.size()==k){
resultList.add(new ArrayList(queue));
return ;
}
for(int i = cur;i<=(n-(k-queue.size())+1);i++){
queue.add(i);
backtracing(n,k,i+1,resultList,queue);
queue.removeLast();
}
}

}

216. Combination Sum III

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]
Explanation:
1 + 2 + 4 = 7
There are no other valid combinations.

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6],[1,3,5],[2,3,4]]
Explanation:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.

Example 3:

Input: k = 4, n = 1
Output: []
Explanation: There are no valid combinations.
Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.

Constraints:

  • 2 <= k <= 9
  • 1 <= n <= 60

正常递归

class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> list = new LinkedList<>();
backtracing(k,n,1,resultList,list);
return resultList;
}
public void backtracing(int k,int n ,int cur,List<List<Integer>> resultList,List<Integer> list){
if(list.size()==k&&getSum(list)==n) {
resultList.add(new ArrayList(list));
}
for(int i=cur;i<=9;i++){
list.add(i);
backtracing(k,n,i+1,resultList,list);
list.removeLast();
}
}
public Integer getSum(List<Integer> list){
int sum = 0;
for(int i = 0;i<list.size();i++){
sum += list.get(i);
}
return sum;
}
}

剪枝优化

class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> list = new LinkedList<>();
backtracing(0,k,n,1,resultList,list);
return resultList;
}
public void backtracing(int sum,int k,int n ,int cur,List<List<Integer>> resultList,List<Integer> list){
if (sum>n) return ;
if(list.size()==k){
if(sum==n){
resultList.add(new ArrayList<>(list));
return;
}
}
for(int i =cur;i<=9-(k-list.size())+1;i++){
sum += i;
list.add(i);
backtracing(sum,k,n,i+1,resultList,list);
list.remove(list.size()-1);
sum -= i ;
}
}
}

17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

img

Example 1:

Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]
class Solution {
String[] letterMap = { "",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz", };
List<String> resultList =new ArrayList<>();

public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return resultList;
}
backtracing(digits,0);
return resultList;
}
StringBuilder temp = new StringBuilder();
public void backtracing(String digits,int index){
if(index==digits.length()){
resultList.add(temp.toString());
return ;
}
String digit = letterMap[digits.charAt(index) - '0'];
for(int i = 0; i<digit.length();i++){
temp.append(digit.charAt(i));
System.out.println("回溯前:"+temp.toString());
backtracing(digits,index + 1);
temp.deleteCharAt(temp.length() - 1);
System.out.println("回溯后:"+temp.toString());
}
2 3

}

}

39. Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the

frequency

of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:

Input: candidates = [2], target = 1
Output: []

Constraints:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40
class Solution {
List<List<Integer>> resultList = new ArrayList<>();
List<Integer> tempList = new LinkedList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
backtracking(candidates,target,0);
return resultList;
}
public void backtracking(int[]candidates,int sum,int index){
if(sum<0){
return;
}
if(sum==0){
resultList.add(new ArrayList<>(tempList));
return ;
}
for(int i = index;i<candidates.length;i++){
if(candidates[i]>sum){
continue;
}
tempList.add(candidates[i]);
sum -= candidates[i];
backtracking(candidates,sum,i);
sum += candidates[i];
tempList.remove(tempList.size()-1);
}
}
}