forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheunhwa99.java
49 lines (38 loc) ยท 1.53 KB
/
eunhwa99.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Arrays;
/**
* ๋ฌธ์ ํ์ด
* ์์ ) 11106
* ๊ฐ์ฅ ํฐ ์๋ 2์๋ฆฌ ์ด๋ฏ๋ก ํ ๋ฒ์ ๊ฐ ์ ์๋ ์นธ์ 1~2์นธ
* ํ์ฌ ์นธ์ด 0์ผ ๊ฒฝ์ฐ๋ ์นธ ์ด๋ ๋ถ๊ฐ
* ์ฝ๋ ๋ฒ์๋ 1~26
*/
//์๊ฐ ๋ณต์ก๋: ๋ฌธ์์ด์ ๊ฐ ์ธ๋ฑ์ค๋ฅผ ํ ๋ฒ์ฉ๋ง ์ฒ๋ฆฌํ๋ฏ๋ก ์ ์ฒด O(n)
//๊ณต๊ฐ ๋ณต์ก๋: dp ๋ฐฐ์ด์ ๋ฌธ์์ด์ ๊ธธ์ด์ ๋น๋กํ์ฌ O(n) ๊ณต๊ฐ์ ์ฐจ์ง
class Solution {
int stringSize = 0;
int[] dp;
// DP ์ด์ฉ
public int numDecodings(String s) {
stringSize = s.length();
dp = new int[stringSize + 1];
Arrays.fill(dp, -1);
return numDecodingHelper(s.toCharArray(), 0);
}
// dp -> O(N)
private int numDecodingHelper(char[] s, int curIndex) {
if (stringSize == curIndex) return 1;
if (s[curIndex] == '0') return 0; // ํ์ฌ ์นธ์ด 0 -> ์ ์ง ๋ถ๊ฐ
if (dp[curIndex] != -1) return dp[curIndex];
dp[curIndex] = 0; // ํ์ฌ ๋
ธ๋ ๋ฐฉ๋ฌธ ์ฒดํฌ
dp[curIndex] += numDecodingHelper(s, curIndex + 1); // ํ ์นธ ์ ์ง
if ((curIndex + 1 < stringSize) && checkRange(s[curIndex], s[curIndex + 1])) // 2์๋ฆฌ ์ฝ๋๊ฐ 10~26 ์์ ๋ค์ด๊ฐ๋ค๋ฉด
dp[curIndex] += numDecodingHelper(s, curIndex + 2); // 2์นธ ์ ์ง
return dp[curIndex];
}
private boolean checkRange(char left, char right) {
int leftNum = left - '0';
int rightNum = right - '0'; // ์ซ์๋ก ๋ณํ
int num = leftNum * 10 + rightNum;
return (num >= 10 && num <= 26);
}
}