Files
hello-algo/ru/codes/c/chapter_dynamic_programming/climbing_stairs_backtrack.c
Yudong Jin 772183705e Add ru version (#1865)
* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
2026-03-28 04:24:07 +08:00

47 lines
1.6 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* File: climbing_stairs_backtrack.c
* Created Time: 2023-09-22
* Author: huawuque404 (huawuque404@163.com)
*/
#include "../utils/common.h"
/* Бэктрекинг */
void backtrack(int *choices, int state, int n, int *res, int len) {
// Когда подъем достигает n-й ступени, число вариантов увеличивается на 1
if (state == n)
res[0]++;
// Перебор всех вариантов выбора
for (int i = 0; i < len; i++) {
int choice = choices[i];
// Отсечение: нельзя выходить за n-ю ступень
if (state + choice > n)
continue;
// Попытка: сделать выбор и обновить состояние
backtrack(choices, state + choice, n, res, len);
// Откат
}
}
/* Подъем по лестнице: бэктрекинг */
int climbingStairsBacktrack(int n) {
int choices[2] = {1, 2}; // Можно подняться на 1 или 2 ступени
int state = 0; // Начать подъем с 0-й ступени
int *res = (int *)malloc(sizeof(int));
*res = 0; // Использовать res[0] для хранения числа решений
int len = sizeof(choices) / sizeof(int);
backtrack(choices, state, n, res, len);
int result = *res;
free(res);
return result;
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsBacktrack(n);
printf("Количество способов подняться по лестнице из %d ступеней: %d\n", n, res);
return 0;
}