반응형
https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/
Number of Ways to Stay in the Same Place After Some Steps - LeetCode
Can you solve this real interview question? Number of Ways to Stay in the Same Place After Some Steps - You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or st
leetcode.com
우측으로 1칸 이동한 경우, 좌측으로 1칸 이동한 경우, 제자리에 남아있는 경우를 모두 검사해주었습니다.
중간 결과는 재사용해줍니다.
dp[steps][idx] = dp[steps - 1][idx + 1] + dp[steps - 1][idx - 1] + dp[steps - 1][idx]
class Solution {
public:
int dp[501][501];
const int MOD = 1e9 + 7;
int numWays(int steps, int arrLen) {
memset(dp, -1, sizeof(dp));
return numWays(steps, arrLen, 0);
}
int numWays(int steps, int arrLen, int idx) {
if(steps == 0) return idx == 0;
if(idx < 0 || idx >= arrLen) return 0;
int& cnt = dp[steps][idx];
if(cnt != -1) return cnt;
return cnt = (
(numWays(steps - 1, arrLen, idx + 1)
+ numWays(steps - 1, arrLen, idx - 1)) % MOD
+ numWays(steps - 1, arrLen, idx)
) % MOD;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 1361. Validate Binary Tree Nodes (0) | 2023.10.18 |
---|---|
LeetCode 119. Pascal's Triangle II (0) | 2023.10.16 |
LeetCode 1095. Find in Mountain Array (0) | 2023.10.12 |
LeetCode 720. Longest Word in Dictionary (0) | 2023.10.09 |
LeetCode 34. Find First and Last Position of Element in Sorted Array (0) | 2023.10.09 |