@iar
2015-03-29T04:34:22.000000Z
字数 2270
阅读 96
leetcode
- N00t大神的recursion出神入化
- LC中大量的recursion解法
- recursion的关键在于代码结构, 以及param/return.
void rec(){
codeTD;
rec();
codeBU;
}
void rec(){
if (lastRow)
res.add(path + s);
for(i = 1; i < path.size(); i++){
rec(path.append, res);
path.delete;
}
}
List<List<?> segmentRec(String s) {
// do something
for ( i ) {
rest = s.substring(i)
for (List<?> seg : segmentRec(rest)) {
// do something
}
}
return result;
}
int DFS(a, sum, minSum) {
sum += a; // walking down the tree.
if (lastRow && sum < minSum) return sum;
else {
minSum = DFS(a, sum, minSum); // 注意这里的赋值是minSum, 而不是其他var name. 所以跟着的第二条recursion中的minSum才会update.
minSum = DFS(a, sum, minSum); // 这里的minSum用于DFS的return.
}
return minSum; // walking up the tree.
}
这个在triangle Path Sum中的N00t的第一个解法.
还有个很好的例子就是flatten Binary Tree的九章算法模版.
Node rec(l, h) {
mid = lo + (hi-lo)/2;
leftNode = rec(lo, mid-1);
middleCode;
rightNode = rec(mid+1, hi);
return root;
}
DFS(tri, row, col, HashMap){
// base condition
return min;
if(Map.contains())
min+= Math.min(DFS(Hashmap), DFS(Hashmap));
else
min+= Math.min(map.get(), DFS(HashMap));
map.put(row, min);
return min;
}