LeetCode Restore IP Addresses (JavaScript), DFS

2026. 3. 5. 18:15·코딩테스트/LeetCode

링크 : https://leetcode.com/problems/restore-ip-addresses/description/

문제 설명

더보기

A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245", "192.168.1.312" and "192.168@1.1" are invalid IP addresses.

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

Example 1:

Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]

Example 2:

Input: s = "0000"
Output: ["0.0.0.0"]

Example 3:

Input: s = "101023"
Output: ["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

Constraints:

  • 1 <= s.length <= 20
  • s consists of digits only.

문제 풀이

접근 방식

  • dfs 함수 인자
    • ip : 현재 저장된 ip 문자열
    • index : 현재 검사할 s의 index
    • part : .의 갯수 (총 4개의 파트로 구성됨)
  • dfs 로직
    1. part가 4인 경우 4개의 파트로 ip 구성이 되었으므로 index가 LENGTH와 같다면 answer에 추가 (맞는 ip)
    2. ip를 만들 수 있는 경우의 수 (최대 3개)
      1. 현재 index를 기준으로 최대 3개까지 설정 가능
        • 2글자 이상인 경우 시작이 0이 아니여야 함
        • 0 ~ 255 사이의 숫자 값으로 되어 있어야 함
      2. 다음 ip를 넘겨줄 때 첫 번째 part(맨 앞 부분의 숫자)가 아니라면 . 을 추가해 ip로 넘겨줌
/**
 * @param {string} s
 * @return {string[]}
 */
var restoreIpAddresses = function(s) {
    const LENGTH = s.length;
    const answer = [];

    const dfs = (ip, index, part) => {
        if (part === 4) {
            if (index === LENGTH) {
                answer.push(ip);
            }
            return;
        }

        for (let len = 1; len <= 3; len++) {
            const nextIndex = index + len;
            if (nextIndex > LENGTH) break;

            const word = s.slice(index, nextIndex);

            if (word.length > 1 && word[0] === '0') continue;
            if (parseInt(word) > 255) continue;

            const nextIp = part === 0 ? word : `${ip}.${word}`;
            dfs(nextIp, nextIndex, part + 1);
        }
    }

    dfs('', 0, 0);

    return answer;
};

결론

part를 사용한 부분이 문제를 좀 더 쉽게 해결할 수 있는 방법 중 하나라고 생각한다.

문제는 DFS로 접근해 해결

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Trapping Rain Water (JavaScript), Two pointer  (0) 2026.03.12
LeetCode Repeated DNA Sequences (JavaScript), Sliding window  (0) 2026.03.06
LeetCode Sudoku (JavaScript), Backtracking  (0) 2026.03.05
LeetCode Combinations (JavaScript), Backtracking  (0) 2026.03.05
LeetCode Gas Station (JavaScript), Greedy  (1) 2026.03.04
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Trapping Rain Water (JavaScript), Two pointer
  • LeetCode Repeated DNA Sequences (JavaScript), Sliding window
  • LeetCode Sudoku (JavaScript), Backtracking
  • LeetCode Combinations (JavaScript), Backtracking
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (252)
      • AI (1)
      • Amazon Cloud (4)
        • EC2 (3)
        • Deploy (1)
      • 프론트엔드 (67)
        • JavaScript (52)
        • HTML (3)
        • React (9)
        • CSS (2)
        • CS (1)
      • 프로젝트 (21)
        • Portfolio 사이트 개발 (21)
      • 코딩테스트 (155)
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (65)
        • LeetCode (62)
      • 자격증 (1)
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Restore IP Addresses (JavaScript), DFS
상단으로

티스토리툴바