-
605. can place flowers카테고리 없음 2022. 3. 28. 17:53
에이스타 알고리즘 도 최적의 해를 (눈앞에 보이는) 쫒는다는 점에서 비슷한 것 같다.
튜플 입력받을때,
(키,벨류) 이런 순서인데
키값 정렬을 lamda 식으로 정렬해준다.인접한 곳에 flower(1) 을 놓을 수 없다.
정답class Solution: def canPlaceFlowers(self, flowerbed: List[int], n :int) ->bool: #bool 형으로 반환 answer = False for i in range(len(flowerbed)): if flowerbed[i] == 0 and (i == 0 or flowerbed[i-1] == 0) and (i == len(flowerbed)-1 or flowerbed[i+1] == 0): #처음 조건이랑 마지막 조건을 넣어준 것이다. i==0 이랑 i == len(flowerbed)-1 이 그런역할을 해주는 것 같다. flowerbed[i] = 1 n -= 1 if n <= 0: answer = True return answer
n 입력값(새로운 꽃을 꽂을수 있는 개수 의미)
n 이 0 이 되면 true 반환
flowerbed = [0] + flowerbed + [0] 처리를 해줘서
경우의 수를 줄이고자 하는 것 같다.def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: if n ==0: return True flowerbed = [0] + flowerbed + [0] size = len(flowerbed) for i in range(1, size-1): if flowerbed[i]: continue elif flowerbed[i - 1] == flowerbed[i + 1] == 0: n-=1 flowerbed[i] = 1 if n == 0:return True return False
n 이 0 일 때 참 값을 반환
continue 일 때, 바로 다음 순번의 loop를 수행합니다.
loop 문을 쓸때, 딱히 할일이 없을 때 이렇게 가는 것 같다.
중요한 코드를 elif 에 밀어넣었다.
확실히 위 코드보다 아래코드가 알아보기 쉬운 것 같다.
답안x, 즉 벨류가 0이어야 not 처리가 되서 1이 되므로,
1이 들어가면(꽃이 채워져있으면) 조건이 1이 안되기 때문에 자동으로 걸러진다!!
은 밑 코드이다.class Solution(object): def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ for i, x in enumerate(A): if (not x and (i == 0 or A[i-1] == 0) and (i == len(A)-1 or A[i+1] == 0)): N -= 1 A[i] = 1 return N <= 0
파이썬이 아닌 언어로 구현