본문 바로가기
코드

Perfect Squares

by ehei 2019. 11. 25.

어떤 정수가 주어졌을 때, 제곱이 되는 수로 어떤 합이 결정되는지 구하는 문제

https://leetcode.com/problems/perfect-squares/

import math


class Solution:
    def numSquares(self, n: int) -> int:
        currentValues = { n }
        count = 0
        
        while currentValues:
            nextValues = set()
            
            for currentValue in currentValues:
                for i in range( 1, int( math.sqrt( currentValue ) ) + 1 ):
                    remainValue = currentValue - i * i
                    
                    if not remainValue:
                        return count + 1
                    elif remainValue > 0:
                        nextValues.add( remainValue )
                        
            currentValues = nextValues
            count += 1
        
        return 0

'코드' 카테고리의 다른 글

Target Sum  (0) 2019.12.04
Clone Graph  (0) 2019.11.26
Open the Lock  (0) 2019.11.04
Number of Islands  (0) 2019.11.04
Design Circular Queue  (0) 2019.11.01