前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Backtracking - 40. Combination Sum II

Backtracking - 40. Combination Sum II

作者头像
ppxai
发布2020-09-23 17:33:17
2770
发布2020-09-23 17:33:17
举报
文章被收录于专栏:皮皮星球皮皮星球

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

思路:

与39题不同的是,数组中同一个元素只能在组合中出现一次,这里只需要先对数组排序,就能去重,做法就和39题一样了。

代码:

代码语言:javascript
复制
func combinationSum2(candidates []int, target int) [][]int {

    var res [][]int
    if candidates == nil || len(candidates) == 0 {
        return res
    }
    sort.Ints(candidates)
    dfs(&res, []int{}, candidates, target, 0)
    return res
}

func dfs(res *[][]int, temp []int, nums []int, target int, start int) {
    if target < 0 {
        return 
    }
    if target == 0 {
        *res = append(*res, append([]int{}, temp...))
    }
    
    for i := start; i < len(nums); i++ {
        if i != start && nums[i] == nums[i-1] {
            continue
        }
        temp = append(temp, nums[i]);
        dfs(res, temp, nums, target - nums[i], i+1)
        temp = temp[:len(temp)-1]
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年09月03日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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