40. Combination Sum II 原

Description

tag: array , backtraking

difficulty : medium

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

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章