40. 组合总和 II @Python @Go

原题

https://leetcode.cn/problems/combination-sum-ii/description/

思路

回溯法, 需要去重

复杂度

时间:O(n * n)
空间:O(n)

Python代码

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        length = len(candidates)
        ans = []

        def dfs(start, curSum, path):
            if curSum == target:
                ans.append(path[:])
                return 
            if curSum > target:
                return
            for i in range(start, length):
                if i > start and candidates[i] == candidates[i-1]:
                    continue 
                curSum += candidates[i]
                path.append(candidates[i])
                dfs(i+1, curSum, path)
                # 还原
                curSum -= candidates[i]
                path.pop()

        dfs(0, 0, [])
        return ans
               

Go代码

func combinationSum2(candidates []int, target int) [][]int {
	sort.Ints(candidates)
	var ans [][]int
	// 匿名函数
	var dfs func(int, int, []int)
	dfs = func(start int, curSum int, path []int) {
		if curSum == target {
			// 拷贝组合
			com := make([]int, len(path))
			copy(com, path)
			ans = append(ans, com)
		}
		if curSum > target {
			return
		}
		for i := start; i < len(candidates); i++ {
			// 去重
			if i > start && candidates[i] == candidates[i-1] {
				continue
			}
			curSum += candidates[i]
			path = append(path, candidates[i])
			dfs(i+1, curSum, path)
			// 还原
			curSum -= candidates[i]
			path = path[:len(path)-1]
		}
	}
	dfs(0, 0, []int{})
	return ans
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值