leetcode 回溯法 模板

来源:互联网 发布:js windows.onload 编辑:程序博客网 时间:2024/06/05 00:43

转自 http://blog.csdn.net/shashafbqc/article/details/25427781


/**
* dfs 模板.
* @param[in] input 输入数据指针
* @param[out] path 当前路径,也是中间结果
* @param[out] result 存放最终结果
* @param[inout] cur or gap 标记当前位置或距离目标的距离
* @return 路径长度,如果是求路径本身,则不需要返回长度
*/
void dfs(type &input, type &path, type &result, int cur or gap) {
    if (数据非法) return 0; // 终止条件
    if (cur == input.size()) { // 收敛条件
        // if (gap == 0) {
        将path 放入result
    }
    if (可以剪枝) return;
    for(...) { // 执行所有可能的扩展动作
        执行动作,修改path
        dfs(input, step + 1 or gap--, result);
        恢复path
    }

}



原创粉丝点击