คำอธิบายโจทย์
อาร์เรย์ขนาด arrLen เริ่ม index 0 แต่ละขั้นตอน: ซ้าย, ขวา, หรืออยู่ที่เดิม หาว่าหลัง steps ก้าว อยู่ index 0 ได้กี่วิธี mod 1e9+7
ตัวอย่าง
steps=3, arrLen=2 → Output: 4
วิธี: [R,L,S], [S,R,L], [R,S,L], [S,S,S]
วิธีแก้ปัญหา
DP 2 มิติ + Space Optimization (rolling array):
- dp[step%2][pos] = วิธีอยู่ pos หลัง step ก้าว
- Transition: dp[y][j] = dp[x][j] + dp[x][j-1] + dp[x][j+1]
- Optimization: pos ไม่เกิน steps/2+1 (ไกลกว่านี้กลับไม่ทัน)
การทำงานของโค้ด
#include <bits/stdc++.h>
using namespace std;
typedef long long lli;
const int MOD = 1e9+7;
lli add(lli a, lli b) { return (a%MOD + b%MOD)%MOD; }
class Solution {
public:
vector<vector<int>> dp;
int solve(int n, int x, int pos=0) { // recursive version
if(x==0) return pos==0;
if(dp[pos][n]!=-1) return dp[pos][n];
int ans=0;
if(pos>0) ans = add(ans, solve(n, x-1, pos-1));
if(pos=0) dp[y][j] = add(dp[y][j], dp[x][j-1]);
if(j+1
อินพุต
3, 2
เอาต์พุต
4