코딩 테스트/LeetCode(swift)

[LeetCode] 377. Combination Sum IV

Skillist 2022. 2. 18. 23:01
반응형

문제

https://leetcode.com/problems/combination-sum-iv/

 

Combination Sum IV - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

———————————————————————————

 

잠깐만

우리가 함께 풀었던 322 Coin Change 문제와 로직의 거의 비슷해요.

https://skillist.tistory.com/253?category=469513 

 

[LeetCode] 322. Coin Change

문제 leetcode.com/problems/coin-change/ Coin Change - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next inte..

skillist.tistory.com

 

———————————————————————————

 

코드

class Solution {
    func combinationSum4(_ nums: [Int], _ target: Int) -> Int {
        var sortedNums = nums.sorted()
        var counts: [Int] = Array(repeating: 0, count: target+1)
        counts[0] = 1
    
        for countIndex in 0...target {
			//if counts[countIndex] == 0 {
			//	continue
			//}
            sortedNums.forEach {
                let nextIndex = countIndex + $0 
                if nextIndex > target {
                    return
                }
                counts[nextIndex] &+= counts[countIndex]
            }
        }
        return counts[target]
    }
}

———————————————————————————

 

설명

322 코인 문제의 계산과 같이, nums의 숫자들을 활용하여,

이전 갯수들로부터 더해나가면 됩니다.

너무 똑같은 로직이기 때문에, 따로 설명하진 않겠습니다.

 

대신 한가지만 설명하겠습니다.

"counts[nextIndex] &+= counts[countIndex]" 에서 활용된 "&+"연산입니다.

playground에서 자꾸 에러가 발생하길래 문제를 찾아봤는데,

바로 해당 라인이었어요.

https://developer.apple.com/documentation/swift/uint/2885903

 

Apple Developer Documentation

 

developer.apple.com

 

공식문서에 다음과 같이 설명돼있습니다.

"지정된 두 값의 합계를 반환하고 오버플로우의 경우 결과를 래핑합니다."

오버플로우 발생 시 오버플로우에 대한 비트를 버리고 값을 처리하네요.

———————————————————————————

 

회고

&+ 부분에서 시간을 많이 소비했습니다. 처음보는 연산이었어요;;;

하나 배워갑니다.

반응형