博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
40. Combination Sum II
阅读量:7040 次
发布时间:2019-06-28

本文共 1798 字,大约阅读时间需要 5 分钟。

  hot3.png

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 [][]intvar existed map[string]intfunc 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

转载于:https://my.oschina.net/liufq/blog/2243629

你可能感兴趣的文章
C#是否简单?
查看>>
测试使用live writer
查看>>
js获取剪贴板内容
查看>>
开始学会记录
查看>>
一个技术人员35岁之前要做的10件事
查看>>
ajax提交form(文本数据以及文件上传)
查看>>
PHP7语法知识(二):流程控制语句、函数、字符串、数组
查看>>
bzoj2426
查看>>
hdu5803
查看>>
拉格朗日插值公式
查看>>
AGC006C Rabbit Exercise
查看>>
2019.1.7 Russia temperature control demo
查看>>
前端学HTTP之内容协商
查看>>
关于C#的数据绑定,存取数据库实例详解 (二)
查看>>
2017年计划
查看>>
一般对话框,单选复选对话框
查看>>
Java ExecutorService 的几种线程池比较
查看>>
个人最终总结
查看>>
关于vs2010开发的ASP项目部署到XPSP2系统上出现找不到Reportviewer.XX.文件的解决方案...
查看>>
CSS中style用法详解
查看>>