我是遞歸的新手,並試圖理解此代碼片段。我正在學習考試,這是我從斯坦福德的CIS教育圖書館(來自Nick Parlante的Binary Trees)發現的「審稿人」。遞歸如何在For循環中工作
我理解這個概念,但是當我們在遞歸在循環內部,這一切的打擊!請幫幫我。謝謝。
countTrees()解決方案(C/C++)
/*
For the key values 1...numKeys, how many structurally unique
binary search trees are possible that store those keys.
Strategy: consider that each value could be the root.
Recursively find the size of the left and right subtrees.
*/
int countTrees(int numKeys) {
if (numKeys <=1) {
return(1);
}
// there will be one value at the root, with whatever remains
// on the left and right each forming their own subtrees.
// Iterate through all the values that could be the root...
int sum = 0;
int left, right, root;
for (root=1; root<=numKeys; root++) {
left = countTrees(root - 1);
right = countTrees(numKeys - root);
// number of possible trees with this root == left*right
sum += left*right;
}
return(sum);
}
我會說它的工作方式完全相同,但我想這不是你想要的那種答案。不要讓'欺騙'欺騙你 - 範圍是重要的。 – rsenna 2011-01-25 15:51:42
你是什麼意思「這一切打擊」?你有沒有崩潰?或者,你的大腦是否在呼吸? – Arkadiy 2011-01-25 21:36:21