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

39. Combination Sum

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

Description

tags : array, backtracking difficulty: medium

代码语言:javascript
代码运行次数:0
运行
复制
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Solution
代码语言:javascript
代码运行次数:0
运行
复制
var results [][]int
var existed map[string]int
func combinationSum(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 _,val := range candidates {
        if val == target {
            result = append(result, val)
            addIfNotExist(result)
            break
        }
        if val < target {
            result = append(result, val)
            backtrack(candidates, target - val, result)
            result = result[0:len(result) - 1]
            continue
        }
        if val > target {
            break
        }
    }
}

func addIfNotExist(result []int){
    var cr []int
    for _,val := range result {
        cr = append(cr, val)
    }
    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
}

Need to consider

  • candidates is empty
  • go slice is replaced in place, so we have to copy it
  • backtracking have duplicate solutions
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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