40. Combination Sum II

2019-07-01 12:03:32 浏览数 (2)

Description

tag: array , backtraking

difficulty : medium

代码语言:javascript复制
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]
]
Solution
代码语言:javascript复制
var results [][]int
var existed map[string]int
func combinationSum2(candidates []int, target int) [][]int {
    results = make([][]int, 0)
    if len(candidates) == 0 {
        return results
    }
    existed = make(map[string]int)
    sort.Ints(candidates)
    backtrack(candidates, target, nil)
    return results
}

func backtrack(candidates []int, target int, result []int){
    for i, val := range candidates {
        if val == target {
            result = append(result, val)
            temp := make([]int, len(result))
            copy(temp, result)
            addIfNotExist(temp)
            break
        }
        if val < target {
            result = append(result, val)
            backtrack(candidates[i 1:], target - val, result)
            result = result[:len(result)-1]
        }
        if val > target {
            break
        }
    }
}
func addIfNotExist(cr []int){
    sort.Ints(cr)
    var s string = ""
    for _, val := range cr {
        s  = ","   string(val)
    }
    if _,ok := existed[s];ok {
        return
    }
    results = append(results, cr)
    existed[s] = 1
}

Note:

  • almost same with 39
  • element can be used only once

0 人点赞