记啃clrs的第三天。此书自带催眠功能。

Recursion is a "Programming Paradigm" which is generally used to implement the "Algorithmic Paradigm" Divide and Conquer .

Ref:http://www.fas.harvard.edu/~cscie119/lectures/recursion.pdf

https://www.cis.upenn.edu/~matuszek/cit594-2012/Pages/backtracking.html

Template for Recursive Backtracking
void findSolutions(n, other params) {
if (found a solution) {
solutionsFound++;
displaySolution();
if (solutionsFound >= solutionTarget)
System.exit(0);
return;
}
for (val = first to last) {
if (isValid(val, n)) {
applyValue(val, n);
findSolutions(n + 1, other params);
removeValue(val, n);
}
}
}

Base case- Bottom out the solution

 

Template for dfs

Template 1: Traverse

public class Solution {
    public void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        // do something with root
        traverse(root.left);
        // do something with root
        traverse(root.right);
        // do something with root
    }
}


Tempate 2: Divide & Conquer

public class Solution {
    public ResultType traversal(TreeNode root) {
        // null or leaf
        if (root == null) {
            // do something and return;
        }
        
        // Divide
        ResultType left = traversal(root.left);
        ResultType right = traversal(root.right);
        
        // Conquer
        ResultType result = Merge from left and right.
        return result;
    }
}

 

posted on 2016-09-19 12:15  Machelsky  阅读(142)  评论(0)    收藏  举报