From ea28577b5e9a12415dcc65ed8349f7478dce69cd Mon Sep 17 00:00:00 2001 From: aucker Date: Tue, 20 Aug 2024 08:23:17 +0800 Subject: [PATCH] Aug20: ways to reach k-th stair [H][DP] Another DP problem w/ states --- daily/Aug20.cc | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 daily/Aug20.cc diff --git a/daily/Aug20.cc b/daily/Aug20.cc new file mode 100644 index 0000000..1615a23 --- /dev/null +++ b/daily/Aug20.cc @@ -0,0 +1,33 @@ +#include +using namespace std; + +class Solution { + public: + /** + * @brief LC3154: Find number of ways to Reach k-th stair [H][DP][State][Memo] + * Time: O() + * + * @param k + * @return int + */ + int waysToReachStair(int k) { + unordered_map memo; + auto dfs = [&](auto&& dfs, int i, int j, bool pre_down) -> int { + if (i > k + 1) { // can't to k + return 0; + } + // compress (i, j, pre_down) to long long + long long mask = (long long)i << 32 | j << 1 | pre_down; + if (memo.find(mask) != memo.end()) { + return memo[mask]; // computed before + } + int res = i == k; + res += dfs(dfs, i + (1 << j), j + 1, false); // op2 + if (i && !pre_down) { + res += dfs(dfs, i - 1, j, true); // op1 + } + return memo[mask] = res; // memo + }; + return dfs(dfs, 1, 0, false); + } +}; \ No newline at end of file