回溯法 Backtracking
Backtracking比较形象来说可以用走迷宫做例子,大多人类一般就是使用回溯法,当走到一条死路,就往回退到前一个岔路,尝试另外一条,直到走出。
简介
中文称做「回溯法」,穷举多维度数据的方法,可以想作是多维度的「穷举搜索」(Exhaustive Search)。
大意是:把多维度数据看做是是一个多维向量(solution vector),然后运用递回依序递回穷举各个维度的值,制作出所有可能的数据(solution space),并且在递回途中避免列举出不正确的数据。
特点
Backtracking的好处,是在递回过程中,能有效的避免列举出不正确的数据,省下很多时间。
另外还可以调整维度的顺序、每个维度中列举值的顺序。如果安排得宜,可以更快的找到数据。
Leetcode 回溯法题目汇总
Tip:只汇总了博主做过的且想的起来的题,可能会继续更新。。
39. Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:[
[7],
[2, 2, 3]
]
Java Code
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> combination = new ArrayList<List<Integer>>();
List<Integer> singleCombination = new ArrayList<Integer>();
Arrays.sort(candidates);
bac