cpp-algo-cases/chapter_dynamic_programming/climbing_stairs_constraint_...

38 lines
856 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: climbing_stairs_constraint_dp.cpp
* Created Time: 2023-07-01
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>Լ<EFBFBD><D4BC><EFBFBD><EFBFBD>¥<EFBFBD>ݣ<EFBFBD><DDA3><EFBFBD>̬<EFBFBD>滮 */
int climbingStairsConstraintDP(int n) {
if (n == 1 || n == 2) {
return 1;
}
// <20><>ʼ<EFBFBD><CABC> dp <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڴ洢<DAB4><E6B4A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľ<EFBFBD>
vector<vector<int>> dp(n + 1, vector<int>(3, 0));
// <20><>ʼ״̬<D7B4><CCAC>Ԥ<EFBFBD><D4A4><EFBFBD><EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľ<EFBFBD>
dp[1][1] = 1;
dp[1][2] = 0;
dp[2][1] = 0;
dp[2][2] = 1;
// ״̬ת<CCAC>ƣ<EFBFBD><C6A3>ӽ<EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD><CFB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
for (int i = 3; i <= n; i++) {
dp[i][1] = dp[i - 1][2];
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
}
return dp[n][1] + dp[n][2];
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsConstraintDP(n);
cout << "<EFBFBD><EFBFBD> " << n << " <20><>¥<EFBFBD>ݹ<EFBFBD><DDB9><EFBFBD> " << res << " <20>ַ<EFBFBD><D6B7><EFBFBD>" << endl;
return 0;
}