定义
回溯算法又叫“试探法”,实际上是一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。
框架
可以按照3个步骤来思考这类的问题:
- 「路径」:记录做出的选择。
- 「选择列表」:通常而言,用数组存储可以选择的操作。
- 「结束条件」:一般而言,就是递归的结束点,也就是搜索的结束点。 ```javascript result = []
function backtrack(路径, 选择列表) { if(‘满足结束条件’) { // 这里就是对答案做更新,依据实际题目出发 result.push(路径) return } else { for(let i = 0; i < 选择列表.length; i++) { // 对一个选择列表做相应的选择
做选择backtrack(路径, 选择列表)// 既然是回溯算法,那么在一次分岔路做完选择后// 需要回退我们之前做的操作撤销选择}}
}
<a name="I1t4K"></a>## leetcode39-组合总和```javascriptvar combinationSum = function (candidates, target) {const ans = []var combination = function (target, combine, index) {if (target === 0) {ans.push(combine)return}if (target < 0) returnif (index === candidates.length) returncombination(target, combine, index + 1)if (target - candidates[index] >= 0) {combination(target - candidates[index], [...combine, candidates[index]], index)}}combination(target, [], 0)return ans;};
