回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。 满足回溯条件的某个状态的点称为“回溯点”。
const result = []; // 存放所欲符合条件结果的集合
const curPath = []; // 存放当前符合条件的结果
const backtracking = (eleList, curPath = [], result = []) => {
if (遇到边界条件) {
result.push(curPath);
} else {
// 枚举可选元素列表
for (let ele of eleList) {
curPath.push(ele);
backtracking(eleList, curPath, result);
path.pop(); // 回溯
}
}
};
// backtracking(eleList)
/**
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
var combine = function (n, k) {
const result = [];
const dfs = (curPath = []) => {
const curPathLen = curPath.length;
if (curPathLen === k) {
result.push(curPath.slice());
} else {
const peek = curPath[curPathLen - 1] || 0;
for (let ele = peek + 1; ele <= n; ++ele) {
curPath.push(ele);
dfs(curPath);
curPath.pop();
}
}
return result;
};
dfs();
return result;
};
/**
* @param {string} s
* @return {string[][]}
*/
var partition = function (s) {
const palindromeStrCache = new Map();
const isPalindromeStr = (str, start, end) => {
const key = `${start},${end}`;
if (palindromeStrCache.has(key)) {
return palindromeStrCache.get(key);
}
if (start >= end) {
palindromeStrCache.set(key, true);
} else if (str[start] === str[end]) {
// 基于 DP 的计算是否是 Palindrome
palindromeStrCache.set(key, isPalindromeStr(str, start + 1, end - 1));
} else {
palindromeStrCache.set(key, false);
}
return palindromeStrCache.get(key);
};
const dfs = (startIndex, curPath, result) => {
const strLen = s.length;
if (startIndex < strLen) {
for (let endIndex = startIndex; endIndex < strLen; ++endIndex) {
if (isPalindromeStr(s, startIndex, endIndex)) {
curPath.push(s.slice(startIndex, endIndex + 1));
// 执行具体的逻辑
dfs(endIndex + 1, curPath, result);
// 回溯
curPath.pop();
}
}
} else {
// 达到终点,加入最终结果
result.push(curPath.slice());
}
return result;
};
return dfs(0, [], []);
};