LeetCode 40. Combination Sum II

题目

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates may only be used once in the combination.

Note:

All numbers (including target) will be positive integers.  
The solution set must not contain duplicate combinations.  
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,  
A solution set is:  
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,  
A solution set is:  
[
  [1,2,2],
  [5]
]

思考

跟combination sum I 类似,只是条件换了一些, 这里要求The solution set must not contain duplicate combinations, 所以主要是处理这些条件

Swift 题解

func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {  
        var result = [[Int]]()

        var current = [Int]()

        let sorted = candidates.sorted()

        dfs(result: &result, current: &current, target: target, level: 0, candidates: sorted)


        return result

    }

    func dfs(result: inout [[Int]], current: inout [Int], target: Int, level: Int, candidates: [Int]) {
        if target == 0 {
            result.append(current)
            return
        }

        if target < 0 {
            return
        }

        for i in level..<candidates.count {
            if i == level {
                current.append(candidates[i])
                dfs(result: &result, current: &current, target: target - candidates[i], level: i + 1, candidates: candidates)
                current.removeLast()
            } else if (candidates[i] != candidates[i - 1]) {
                current.append(candidates[i])
                dfs(result: &result, current: &current, target: target - candidates[i], level: i + 1, candidates: candidates)
                current.removeLast()
            }

        }
    }

chenbo

编程爱好者

Singapore