Nailer's blog

Leetcode subset(Python)

January 2nd, 2020


ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์—์„œ ์ฃผ๋กœ ์ƒ์ฃผํ•˜๊ณ  ๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ leetcode์˜ ๋ฌธ์ œ๋“ค์„ ๋งค์ผ ์ œ์‹œํ•˜๊ณ  ํ‘ธ๋Š” ์นดํ†ก๋ฐฉ์— ๋“ค์–ด์˜จ ๊น€์— ํ’€์ด๋ฅผ ์จ๋ณด๋ ค๊ณ  ํ•ด์š”. ๊พธ์ค€ํ–ˆ์œผ๋ฉด ์ข‹๊ฒ ์–ด์š”!

๋ฌธ์ œ ๋งํฌ

์ ‘๊ทผ (์˜์‹์˜ ํ๋ฆ„)

๊ฐ’์ด ๋ชจ๋‘ ๋‹ค๋ฅธ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ๋ถ€๋ถ„ ์ง‘ํ•ฉ์„ ๋Œ๋ ค์ฃผ๋Š” method๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๋ฌธ์ œ์—์š”. python์—๋Š” itertools ์—์„œ combinations ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ‘ธ๋Š” ๋ฐฉ๋ฒ•์„ ์ œ์ผ ๋จผ์ € ๋– ์˜ฌ๋ ธ๊ณ , ์ž‘์„ฑํ•œ ์ฝ”๋“œ๊ฐ€ ํ†ต๊ณผํ–ˆ์–ด์š”. ๊ทธ๋Ÿฐ๋ฐ ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ๋‹ต์„ ๋ณด๋‹ˆ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๋‹ต๋“ค์ด ๋งŽ์•„์„œ reduce ๋งŒ ์‚ฌ์šฉํ–ˆ์–ด์š”. ๋•๋ถ„์— ์ „์ฒด 4์ค„ ์งœ๋ฆฌ ์ฝ”๋“œ๋กœ ํ†ต๊ณผํ–ˆ์–ด์š”.

์ฝ”๋“œ

from functools import reduce
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        return reduce(lambda x, y: x + [i + [y] for i in x], nums, [[]])

image-20200102210024153

์„ฑ๋Šฅ์—์„œ๋Š” ํฐ ์ฐจ์ด๊ฐ€ ์—†์—ˆ์–ด์š”.

Created by SeongHeum CHOI, 2020