Files
hello-algo/ja/codes/cpp/chapter_dynamic_programming/climbing_stairs_backtrack.cpp
Ikko Eltociear Ashimine 954c45864b docs: add Japanese translate documents (#1812)
* docs: add Japanese documents (`ja/docs`)

* docs: add Japanese documents (`ja/codes`)

* docs: add Japanese documents

* Remove pythontutor blocks in ja/

* Add an empty at the end of each markdown file.

* Add the missing figures (use the English version temporarily).

* Add index.md for Japanese version.

* Add index.html for Japanese version.

* Add missing index.assets

* Fix backtracking_algorithm.md for Japanese version.

* Add avatar_eltociear.jpg. Fix image links on the Japanese landing page.

* Add the Japanese banner.

---------

Co-authored-by: krahets <krahets@163.com>
2025-10-17 05:04:43 +08:00

42 lines
1.2 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.cpp
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* バックトラッキング */
void backtrack(vector<int> &choices, int state, int n, vector<int> &res) {
// n段目に到達したとき、解の数に1を加える
if (state == n)
res[0]++;
// すべての選択肢を走査
for (auto &choice : choices) {
// 剪定n段を超えて登ることを許可しない
if (state + choice > n)
continue;
// 試行:選択を行い、状態を更新
backtrack(choices, state + choice, n, res);
// 撤回
}
}
/* 階段登り:バックトラッキング */
int climbingStairsBacktrack(int n) {
vector<int> choices = {1, 2}; // 1段または2段登ることを選択可能
int state = 0; // 0段目から登り始める
vector<int> res = {0}; // res[0] を使用して解の数を記録
backtrack(choices, state, n, res);
return res[0];
}
/* ドライバーコード */
int main() {
int n = 9;
int res = climbingStairsBacktrack(n);
cout << n << "段の階段を登る解は" << res << "通りです" << endl;
return 0;
}