728x90
반응형
문제 링크
https://leetcode.com/problems/4sum/
문제 설명
제한사항
- 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 |
---|