Zero to Hero
article thumbnail
Published 2021. 10. 7. 23:32
타겟 넘버 Algorithm
 

코딩테스트 연습 - 타겟 넘버

n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+

programmers.co.kr

 

반올림 2년 전 코드

def solution(list1, target):
    stack1=[(1,list1[0])]
    visited1=[]
    length=len(list1)

    while stack1:
        item=stack1.pop()
        if item[0]==length:
            visited1.append(item)
        if item[0]<length:
            visited1.append(item)
            stack1.append((item[0]+1,item[1]+list1[item[0]]))
            stack1.append((item[0] + 1, item[1]-list1[item[0]]))

    stack2 = [(1, -list1[0])]
    visited2 = []
    length = len(list1)

    while stack2:
        item = stack2.pop()
        if item[0]==length:
            visited2.append(item)
        if item[0]<length:
            visited2.append(item)
            stack2.append((item[0] + 1, item[1] + list1[item[0]]))
            stack2.append((item[0] + 1, item[1] - list1[item[0]]))

    # print(visited1)
    # print(visited2)
    # print(visited1+visited2)
    visited_merge=visited1+visited2
    visited_merge.sort(key=lambda x:x[0],reverse=True)
    counter=0
    # print(visited_merge)
    for i in range(len(visited_merge)):
        if visited_merge[i][0]==length and visited_merge[i][1]==target:
            counter+=1
    return counter

 

다시 쓴 코드

def solution(nums, target):
    stack = [(0, 0)]
    answer = 0
    while stack:
        cur_val, cur_length = stack.pop()
        if cur_length == len(nums):
            answer += 1 if cur_val == target else 0
            continue

        stack.append((cur_val + nums[cur_length], cur_length + 1))
        stack.append((cur_val - nums[cur_length], cur_length + 1))
    return answer

itertools.product()

from itertools import product


def solution(nums, target):
    products = product([-1, 1], repeat=len(nums))
    answer = 0
    for p in products:
        answer += 1 if sum(x * y for x, y in zip(nums, p)) == target else 0
    return answer

 

 

과거의 나는 무슨 생각을 하고 있었던 걸까...

 

'Algorithm' 카테고리의 다른 글

33. Search in Rotated Sorted Array  (0) 2021.10.11
34. Find First and Last Position of Element in Sorted Array  (0) 2021.10.11
2477번: 참외밭  (0) 2021.10.05
567. Permutation in String  (0) 2021.10.02
189. Rotate Array  (0) 2021.09.28
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!