leetcode-40 组合总和 II

相关:

leetcode-46 全排列
leetcode-47 全排列 II

leetcode-39 组合总和
leetcode-40 组合总和 II


40. 组合总和 II

难度: 中等

面试一点资讯时被问到


接近版:

1
2
3
4
给一个仅包含正整数的无重复元素的数组,找出和为n的所有不重复组合;
input: [1,2,3,4,6] 10

output: [1,2,3,4],[1,3,6],[4,6]

Leetcode No.40 组合总和 II(DFS)

  • 要求出总和为 sum 的所有组合,组合需要去重。这一题是第 39 题的加强版,第 39 题中元素可以重复利用(重复元素可无限次使用),这一题中元素只能有限次数的利用,因为存在重复元素,并且每个元素只能用一次(重复元素只能使用有限次)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
"sort"
)

func combinationSum2(candidates []int, target int) [][]int {
if len(candidates) == 0 {
return [][]int{}
}
c, res := []int{}, [][]int{}
sort.Ints(candidates) // 这里是去重的关键逻辑
findcombinationSum2(candidates, target, 0, c, &res)
return res
}

func findcombinationSum2(nums []int, target, index int, c []int, res *[][]int) {
if target == 0 {
b := make([]int, len(c))
copy(b, c)
*res = append(*res, b)
return
}
for i := index; i < len(nums); i++ {
if i > index && nums[i] == nums[i-1] { // 这里是去重的关键逻辑,本次不取重复数字,下次循环可能会取重复数字
continue
}
if target >= nums[i] {
c = append(c, nums[i])
findcombinationSum2(nums, target-nums[i], i+1, c, res)
c = c[:len(c)-1]
}
}
}

文章目录