【发布时间】:2014-04-24 01:33:40
【问题描述】:
此函数旨在生成楼梯上大步和短步的组合数(用户给出的值)。小步幅为 1 步,大步幅为 2 步。
但是,我不明白这里使用的递归洞察力。我真的很感激解释为什么这会产生所需的组合数量。通过它,我可以看到它有效,但 我不确定我自己是如何得出这个逻辑的。
有人可以对此有所了解吗?
代码如下:
int CountWays(int numStairs);
int combination_strides = 0;
const int LARGE_STEP = 2;
const int SMALL_STEP = 1;
int main() {
cout << "Enter the number of stairs you wish to climb: ";
int response = GetInteger();
int combinations = CountWays(response);
cout << "The number of stride combinations is: " << combinations << endl;
return 0;
}
int CountWays(int numStairs) {
if (numStairs < 4) {
return numStairs;
} else {
return CountWays(numStairs - SMALL_STEP) + CountWays(numStairs - LARGE_STEP);
}
}
【问题讨论】: