LeetCode - 解题笔记 - 39 - Combination Sum

Combination Sum

Solution 1

啊哈又是一个DFS,还是N皇后的思路,只是状态上不是每一步只能用一次而是无限次。因此再状态切换上的两个状态为:

  1. 选择当前位置,下一次递归搜索只要target值还够,就继续考察当前位置
  2. 不选择当前位置,搜索下一个位置,上一种情况在target值不够的情况下会自动归约到这个状态

此外优化方面再加一个剪枝,先排序一下整个数组,如果当前索引位置的值已经不够target,后面就都不用搜索了。

  • O ( n ⋅ 2 n ) O(n \cdot 2^n) O(n2n),初步算的是这个,官方题解给出的那个更紧的上界我不是很懂
  • O ( n ⋅ t a r g e t ) O(n \cdot target) O(ntarget),递归占用最坏是下到target层(target个1相加),所有数字最坏保存n个target长的数组结果(官网算的更紧,但是好像只考虑了递归调用?)
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> ans;
        vector<int> tmp;
        sort(candidates.begin(), candidates.end());
        
        this->dfs(candidates, target, ans, tmp, 0);
        
        return ans;
    }
private:
    void dfs(vector<int> & candidates, int target, vector<vector<int>> & ans, vector<int> & tmp, int index) {
        if (index >= candidates.size()) {
            return;
        }
        
        if (target == 0) {
            ans.push_back(tmp);
            return;
        }
        
        
        if (target - candidates[index] >= 0) {
            // 选择当前索引位置
            tmp.push_back(candidates[index]);
            // 这里不增加,因为可以无限次用当前位置
            this->dfs(candidates, target - candidates[index], ans, tmp, index);
            tmp.pop_back();
            
            // 跳过当前位置,向下一个位置搜索
            this->dfs(candidates, target, ans, tmp, index + 1);
        }
        
    }
};

Solution 2

Solution 1的Python实现,注意Python函数调用的引用传值特性

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        ans = list()
        tmp = list()
        
        candidates = sorted(candidates)
        
        self.__dfs(candidates, target, ans, tmp, 0)
        
        return ans
    
    def __dfs(self, candidates: List[int], target: int, ans: List[List[int]], tmp: List[int], index: int) -> None:
        # print(ans, target, tmp, index)
        if index >= len(candidates): return 
        if target == 0: 
            ans.append(deepcopy(tmp))
            # print(ans)
            return
        
        if target - candidates[index] >= 0:
            tmp.append(candidates[index])
            self.__dfs(candidates, target - candidates[index], ans, tmp, index)
            tmp.pop()
            
            self.__dfs(candidates, target, ans, tmp, index + 1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值