본문 바로가기
알고리즘

[Swift] LeetCode - 39. Combination Sum

by 고고 2022. 2. 16.

문제: https://leetcode.com/problems/combination-sum/

 

Combination Sum - 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

 

 

조합을 응용해서 했습니다.

import Foundation

class Solution {
    func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
        var result = [[Int]]()
        
        func combination(_ index: Int, _ nowCombi: [Int]) {
            if nowCombi.reduce(0, +) == target {
                result.append(nowCombi)
                return
            } else if nowCombi.reduce(0, +) > target {
                return
            }
            
            for i in index..<candidates.count {
                combination(i, nowCombi + [candidates[i]])
            }
        }
        
        combination(0, [])
        
        return result
    }
}

print(Solution().combinationSum([2,3,6,7], 7)) // [[2,2,3],[7]]
print(Solution().combinationSum([2,3,5], 8)) // [[2,2,2,2],[2,3,3],[3,5]]
print(Solution().combinationSum([2], 1)) // []

 

 

댓글