cpp-algo-cases/chapter_dynamic_programming/climbing_stairs_backtrack.cpp

44 lines
1.0 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: climbing_stairs_backtrack.cpp
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD> */
void backtrack(vector<int> &choices, int state, int n, vector<int> &res) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> n <20><>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1
if (state == n)
res[0]++;
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
for (auto &choice : choices) {
// <20><>֦<EFBFBD><D6A6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Խ<EFBFBD><D4BD><EFBFBD><EFBFBD> n <20><>
if (state + choice > n)
continue;
// <20><><EFBFBD>ԣ<EFBFBD><D4A3><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD>񣬸<EFBFBD><F1A3ACB8><EFBFBD>״̬
backtrack(choices, state + choice, n, res);
// <20><><EFBFBD><EFBFBD>
}
}
/* <20><>¥<EFBFBD>ݣ<EFBFBD><DDA3><EFBFBD><EFBFBD><EFBFBD> */
int climbingStairsBacktrack(int n) {
vector<int> choices = {1, 2}; // <20><>ѡ<EFBFBD><D1A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1 <20>׻<EFBFBD> 2 <20><>
int state = 0; // <20>ӵ<EFBFBD> 0 <20>׿<EFBFBD>ʼ<EFBFBD><CABC>
vector<int> res = {0}; // ʹ<><CAB9> res[0] <20><>¼<EFBFBD><C2BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
backtrack(choices, state, n, res);
return res[0];
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsBacktrack(n);
cout << "<EFBFBD><EFBFBD> " << n << " <20><>¥<EFBFBD>ݹ<EFBFBD><DDB9><EFBFBD> " << res << " <20>ַ<EFBFBD><D6B7><EFBFBD>" << endl;
return 0;
}