반응형
롯데V3
롯데 우승하는 그날까지 개발...ing
롯데V3
전체 방문자
오늘
어제
  • 분류 전체보기 (216)
    • Computer Science (0)
      • 운영체제 (0)
    • Problem Solving (160)
      • 프로그래머스 (93)
      • 백준 (60)
      • 리트코드 (2)
      • SQL (5)
    • 언어 (8)
      • 파이썬 (8)
    • 취준 (1)
      • 합격후기 (1)
    • 도서 리뷰 (21)
      • IT 도서 리뷰 (20)
      • 기타 도서 리뷰 (1)
    • 논문 리뷰 (1)
    • 회고 (5)
      • TIL (5)
    • 머신러닝 (9)
      • 통계 (3)
      • 전처리 (1)
      • 클러스터링 (3)
    • 딥러닝 (3)
      • 자연어처리 (1)
      • LLM (1)
    • 프로젝트 (5)
    • Util (0)
    • Tool (1)
      • Poetry (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 티스토리챌린지
  • DP

최근 댓글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
롯데V3

롯데 우승하는 그날까지 개발...ing

[리트코드] 18. 4Sum
Problem Solving/리트코드

[리트코드] 18. 4Sum

2023. 7. 11. 10:46
728x90
반응형

문제 링크

https://leetcode.com/problems/4sum/

 

4Sum - LeetCode

Can you solve this real interview question? 4Sum - Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: * 0 <= a, b, c, d < n * a, b, c, and d are distinct. * nums[a] + nums[b] +

leetcode.com


문제 설명


제한사항

  • 1 <= nums.length <= 200
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109

입출력 예

Example 1:

Input: nums = [1, 0, -1, 0, -2, 2], target = 0
Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

Example 2:

 

Input: nums = [2, 2, 2, 2, 2], target = 8
Output: [[2, 2, 2, 2]]

풀이 과정

정답

  • 3중 for 문.
from collections import defaultdict
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        answer = set()

        n = len(nums)

        checked = defaultdict(bool)

        for a in range(n):
            for b in range(a+1, n):
                for c in range(b+1, n):
                    nums_d = target - nums[a] - nums[b] - nums[c]
                    if checked[nums_d] == True:
                        sub = sorted([nums[a], nums[b], nums[c], nums_d])
                        answer.add((sub[0], sub[1], sub[2], sub[3]))
                        
            checked[nums[a]] = True

        answer = list(answer)

        return answer

 

728x90
반응형
저작자표시 (새창열림)

'Problem Solving > 리트코드' 카테고리의 다른 글

[리트코드] 11. Container With Most Water  (0) 2023.07.10
    'Problem Solving/리트코드' 카테고리의 다른 글
    • [리트코드] 11. Container With Most Water
    롯데V3
    롯데V3

    티스토리툴바