cpp-algo-cases/chapter_dynamic_programming/climbing_stairs_dfs_mem.cpp

40 lines
848 B
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: climbing_stairs_dfs_mem.cpp
* Created Time: 2023-06-30
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD><E4BBAF><EFBFBD><EFBFBD> */
int dfs(int i, vector<int> &mem) {
// <20><>֪ dp[1] <20><> dp[2] <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֮
if (i == 1 || i == 2)
return i;
// <20><><EFBFBD><EFBFBD><EFBFBD>ڼ<EFBFBD>¼ dp[i] <20><><EFBFBD><EFBFBD>ֱ<EFBFBD>ӷ<EFBFBD><D3B7><EFBFBD>֮
if (mem[i] != -1)
return mem[i];
// dp[i] = dp[i-1] + dp[i-2]
int count = dfs(i - 1, mem) + dfs(i - 2, mem);
// <20><>¼ dp[i]
mem[i] = count;
return count;
}
/* <20><>¥<EFBFBD>ݣ<EFBFBD><DDA3><EFBFBD><EFBFBD><EFBFBD><E4BBAF><EFBFBD><EFBFBD> */
int climbingStairsDFSMem(int n) {
// mem[i] <20><>¼<EFBFBD><C2BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD> i <20>׵ķ<D7B5><C4B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>-1 <20><><EFBFBD><EFBFBD><EFBFBD>޼<EFBFBD>¼
vector<int> mem(n + 1, -1);
return dfs(n, mem);
}
/* Driver Code */
int main() {
int n = 9;
int res = climbingStairsDFSMem(n);
cout << "<EFBFBD><EFBFBD> " << n << " <20><>¥<EFBFBD>ݹ<EFBFBD><DDB9><EFBFBD> " << res << " <20>ַ<EFBFBD><D6B7><EFBFBD>" << endl;
return 0;
}