首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >40. Combination Sum II

40. Combination Sum II

作者头像
Dylan Liu
发布2019-07-01 12:03:32
发布2019-07-01 12:03:32
34300
代码可运行
举报
文章被收录于专栏:dylanliudylanliu
运行总次数:0
代码可运行
Description

tag: array , backtraking

difficulty : medium

代码语言:javascript
代码运行次数:0
运行
复制
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
代码运行次数:0
运行
复制
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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Description
  • Solution
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档