- μ«μλ‘ ννλ μνλ²³ λ¬Έμμ΄μ ν΄μν μ μλ κ²½μ°μ μλ₯Ό ꡬνλ€.
- μλ₯Όλ€μ΄
111
μ aaa 1 1 1
, ak 1 11
, ka 11 1
λ‘ ν΄μλ μ μλ€. 0
μ κ²½μ° 106
μ 1 06
κ³Ό κ°μ΄ μμ 0
μ΄ μ€λ ννλ‘ λ¬Άμ΄μ ν΄μν μ μμμ μ£Όμνλ€.
- 첫λ²μ§Έ indexλΆν° μμ°¨μ μΌλ‘ ν΄μμ μ§ννλ€.
- νμ¬ μ리μ μ«μλ₯Ό ν΄μνκ³ indexλ₯Ό μ¦κ°μν¨λ€.
- μ«μκ°
0
μ΄λ©΄ μλͺ»ν΄μν κ²μ΄λ―λ‘ κ²½μ°μ μκ° μλκ² 0 μΌλ‘ νλ€. - μ«μκ°
1
μ΄κ³ λ€μ μ«μκ° μ‘΄μ¬νλ©΄ νμ¬ μ«μλ§μΌλ‘ ν΄μν κ²½μ° index +1
+ λ€μμ«μκΉμ§ λ¬Άμ΄μ ν΄μν κ²½μ° index +2
μ μλ₯Ό λν κ²μ κ²°κ³Όλ‘ νλ€. - μ«μκ°
2
μ΄κ³ λ€μ μ«μκ° 0~6
μΈ κ²½μ° νμ¬ μ«μλ§μΌλ‘ ν΄μν κ²½μ° + λ€μμ«μκΉμ§ λ¬Άμ΄μ ν΄μν κ²½μ°μ μλ₯Ό λν κ²μ κ²°κ³Όλ‘ νλ€. - λλ¨Έμ§ κ²½μ°μλ νμ¬ μ«μλ§μΌλ‘ ν΄μν κ²½μ°μ μλ₯Ό λλ €μ€λ€.
- Indexκ° λ¬Έμμ΄ λμ λλ¬ν κ²½μ° ν΄μν μ μλ κ²½μ°μ μλ νκ°μ§ λΏμ΄λ―λ‘ κ²°κ³Ό κ°μ
1
μ΄ λλ€.
- μμ λ‘μ§μ κ·Έλ₯ ꡬννκ² λλ©΄ μ¬κ·νΈμΆλ‘ μΈν΄ μκ° μ μ½μ 걸릴 μ μλ€.
- μλ₯Όλ€μ΄ 1λ‘λ§ μ΄λ£¨μ΄μ§ κΈΈμ΄ μΈ λ¬Έμμ΄μ΄ μμ λ μ¬κ·νΈμΆμ μλ μ΄ λλ―λ‘ λ¬Έμ κ° λ μ μλ€.
- μ΄μ°¨νΌ νΉμ index μ΄νλ₯Ό ν΄μνλ κ²½μ°μ μλ λμΌνλ―λ‘ memoizationμ μ΄μ©νμ¬ μ€λ³΅λ μ°μ°μ μ€μΈλ€.
class Solution {
public int traverse(String s, int[] dp, int index) {
if (dp[index] != -1) return dp[index];
int curr = s.charAt(index) - '0';
if (curr == 0) return dp[index] = 0;
if (curr == 1 || curr == 2) {
if (index + 1 < s.length()) {
int next = s.charAt(index + 1) - '0';
boolean isValidNext =
curr == 1 || (curr == 2 && next <= 6);
if (isValidNext) {
return dp[index] =
traverse(s, dp, index + 1) +
traverse(s, dp, index + 2);
}
}
}
return dp[index] = traverse(s, dp, index + 1);
}
public int numDecodings(String s) {
int[] dp = new int[s.length() + 1];
Arrays.fill(dp, -1);
dp[s.length()] = 1;
return traverse(s, dp, 0);
}
}