파비의 매일매일 공부기록

2023.11.11 Today's Challenge 본문

Problem Solving/LeetCode

2023.11.11 Today's Challenge

fabichoi 2023. 11. 11. 23:45

https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/

 

Restore the Array From Adjacent Pairs - LeetCode

Can you solve this real interview question? Restore the Array From Adjacent Pairs - There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are give

leetcode.com

DFS로 푸는 문제.
인접 리스트를 만들어서 풀면 될 것 같다는 생각이 어렴풋이 들긴 했는데 결국 못품 ㅠㅠ
그래도 로컬에서 디버깅 하면서 어떤 개념으로 돌아가는지 눈으로 한번 더 확인함.
사실 모르면 안되는 부분일 수 있긴한데.. 뭐 다음에는 해설 안보고 인접 리스트까지 만드는 것만 해도 충분 할 듯

class Solution:
    def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
        gr = defaultdict(list)

        for x, y in adjacentPairs:
            gr[x].append(y)
            gr[y].append(x)
                    
        root = None 
        for n in gr:
            if len(gr[n]) == 1:
                root = n
                break
            
        def dfs(node, prev, ans):
            ans.append(node)
            for nei in gr[node]:
                if nei != prev:
                    dfs(nei, node, ans)
            
        ans = []
        dfs(root, None, ans)
        return ans
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.11.13 Today's Challenge  (0) 2023.11.13
2023.11.12 Today's Challenge  (0) 2023.11.12
2023.11.10 Today's Challenge  (0) 2023.11.10
2023.11.09 Today's Challenge  (0) 2023.11.09
2023.11.08 Today's Challenge  (0) 2023.11.08
Comments