cpp-algo-cases/chapter_dynamic_programming/climbing_stairs_dp.cpp

50 lines
1.0 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: climbing_stairs_dp.cpp
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>¥<EFBFBD>ݣ<EFBFBD><DDA3><EFBFBD>̬<EFBFBD>滮 */
int climbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// <20><>ʼ<EFBFBD><CABC> dp <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڴ洢<DAB4><E6B4A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľ<EFBFBD>
vector<int> dp(n + 1);
// <20><>ʼ״̬<D7B4><CCAC>Ԥ<EFBFBD><D4A4><EFBFBD><EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ľ<EFBFBD>
dp[1] = 1;
dp[2] = 2;
// ״̬ת<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] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* <20><>¥<EFBFBD>ݣ<EFBFBD><DDA3>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>滮 */
int climbingStairsDPComp(int n) {
if (n == 1 || n == 2)
return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int tmp = b;
b = a + b;
a = tmp;
}
return b;
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsDP(n);
cout << "<EFBFBD><EFBFBD> " << n << " <20><>¥<EFBFBD>ݹ<EFBFBD><DDB9><EFBFBD> " << res << " <20>ַ<EFBFBD><D6B7><EFBFBD>" << endl;
res = climbingStairsDPComp(n);
cout << "<EFBFBD><EFBFBD> " << n << " <20><>¥<EFBFBD>ݹ<EFBFBD><DDB9><EFBFBD> " << res << " <20>ַ<EFBFBD><D6B7><EFBFBD>" << endl;
return 0;
}