Skip to content

Commit a01bdcd

Browse files
committed
chapter_dynamic_programming: climbing_stairs_backtrack1.c
1 parent 2a2da47 commit a01bdcd

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include "../utils/common.h"
2+
3+
/* 回溯 */
4+
void backtrack(int *choices, int state, int n, int *res, int len) {
5+
// 当爬到第 n 阶时,方案数量加 1
6+
if (state ==n)
7+
res[0]++;
8+
// 遍历所有选择
9+
for (int i = 0; i < len; i++) {
10+
int choice = choices[i];
11+
// 剪枝:不允许越过第 n 阶
12+
if (state + choice > n)
13+
continue;
14+
// 尝试:做出选择,更新状态
15+
backtrack(choices, state + choice, n ,res, len);
16+
// 回退
17+
}
18+
}
19+
20+
/* 爬楼梯:回溯 */
21+
int climbingStairsBacktrack(int n) {
22+
int choices[2] = {1, 2}; // 可选择向上爬 1 阶或 2阶
23+
int state = 0; // 从第 0 阶开始爬
24+
int *res = (int *)malloc(sizeof(int));
25+
*res = 0; // 使用 res[0] 记录方案数量
26+
int len = sizeof(choices) / sizeof(int);
27+
backtrack(choices, state, n ,res, len);
28+
int result = *res;
29+
free(res);
30+
return result;
31+
}
32+
33+
/* Driver Code */
34+
int main() {
35+
int n = 9;
36+
int res = climbingStairsBacktrack(n);
37+
printf("爬 %d 阶楼梯共有 %d 种方案\n", n, res);
38+
39+
return 0;
40+
}

0 commit comments

Comments
 (0)