Leetcode40 Combination Sum II

题目地址:
https://leetcode.com/problems/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.
分析:
简单做法就是用递归,用python实现了,见代码1。需要注意有注释的那行,保障了not contain duplicate combinations.

又考虑了非递归做法,用cpp实现了(好久不用cpp,就当复习了),见代码2。
代码1:

class Solution(object):
    def combinationSum2(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        result = []
        one = []

        def recursion(idx, sum):
            for x in range(idx, len(candidates)):
                if x != idx and candidates[x] == candidates[x - 1]:  # 同一个slot,不放入相同的值
                    continue
                one.append(candidates[x])
                sum = _sum = sum + candidates[x]
                if _sum < target:
                    recursion(x + 1, sum)
                elif sum == target:
                    result.append(one[:])
                t = one.pop()
                sum -= t
                if _sum >= target:
                    break

        recursion(0, 0)
        return result

代码2:
 

class Solution {
public:
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		vector<vector<int>> result;
		vector<int> idxs;
		int idx = 0;
		int sum = 0;
		sort(candidates.begin(), candidates.end());
		idxs.push_back(idx);
		sum += candidates[idx];
		do {
			bool is_push = true;
			if (sum >= target) { // 1.继续push的话会超过target
				if (sum == target) {
					vector<int> tmp;
					for (auto iter = idxs.begin(); iter != idxs.end(); iter++)
						tmp.push_back(candidates[*iter]);
					result.push_back(tmp);
				}
				is_push = false;
			}
			idx = idxs.back();  // 2. 没有可以push的数了
			if (idx == candidates.size() - 1)
				is_push = false;

			if (is_push) { // 继续push
				idxs.push_back(idx + 1);
				sum += candidates[idx + 1];
			}
			else { // pop队尾,直到队尾可以修改为合理值
				while (idxs.size()) {
					sum -= candidates[idxs.back()];
					idxs.pop_back();
					if (idxs.size()) {
						idx = idxs.back();
						if (candidates[idx] != candidates.back()) {
							do {
								idx++;
							} while (candidates[idx] == candidates[idx - 1]);
							break;
						}
					}
				}
				if (idxs.size()) {
					sum -= candidates[idxs.back()];
					idxs[idxs.size() - 1] = idx;
					sum += candidates[idx];
				}
			}
		} while (idxs.size());
		return result;
	}
};

 

最后!吐槽下现在的优快云 #¥%……&*

C语言-光伏MPPT算法:电导增量法扰动观察法+自动全局搜索Plecs最大功率跟踪算法仿真内容概要:本文档主要介绍了一种基于C语言实现的光伏最大功率点跟踪(MPPT)算法,结合电导增量法与扰动观察法,并引入自动全局搜索策略,利用Plecs仿真工具对算法进行建模与仿真验证。文档重点阐述了两种经典MPPT算法的原理、优缺点及其在不同光照和温度条件下的动态响应特性,同时提出一种改进的复合控制策略以提升系统在复杂环境下的跟踪精度与稳定性。通过仿真结果对比分析,验证了所提方法在快速性和准确性方面的优势,适用于光伏发电系统的高效能量转换控制。; 适合人群:具备一定C语言编程基础和电力电子知识背景,从事光伏系统开发、嵌入式控制或新能源技术研发的工程师及高校研究人员;工作年限1-3年的初级至中级研发人员尤为适合。; 使用场景及目标:①掌握电导增量法与扰动观察法在实际光伏系统中的实现机制与切换逻辑;②学习如何在Plecs中搭建MPPT控制系统仿真模型;③实现自动全局搜索以避免传统算法陷入局部峰值问题,提升复杂工况下的最大功率追踪效率;④为光伏逆变器或太阳能充电控制器的算法开发提供技术参考与实现范例。; 阅读建议:建议读者结合文中提供的C语言算法逻辑与Plecs仿真模型同步学习,重点关注算法判断条件、步长调节策略及仿真参数设置。在理解基本原理的基础上,可通过修改光照强度、温度变化曲线等外部扰动因素,进一步测试算法鲁棒性,并尝试将其移植到实际嵌入式平台进行实验验证。
### LeetCode Problem 40 的 C++ 实现 LeetCode40 题名为 **Combination Sum II**,其目标是从给定候选数组 `candidates` 中找出所有不同的组合,使得这些数的和等于目标值 `target`。需要注意的是,每个数字只能使用一次,并且解集中不能包含重复的组合。 以下是该问题的一个标准回溯法 (Backtracking) 解决方案: ```cpp class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); // 排序以便去重 vector<vector<int>> result; vector<int> path; backtrack(result, path, candidates, target, 0); return result; } private: void backtrack(vector<vector<int>>& result, vector<int>& path, vector<int>& candidates, int remain, int start) { if (remain < 0) return; // 超过目标值则返回 if (remain == 0) { // 找到符合条件的组合 result.push_back(path); return; } for (int i = start; i < candidates.size(); ++i) { // 去除重复组合 if (i > start && candidates[i] == candidates[i - 1]) continue; path.push_back(candidates[i]); // 选择当前元素 backtrack(result, path, candidates, remain - candidates[i], i + 1); // 进入下一层决策树 path.pop_back(); // 撤销选择 } } }; ``` #### 复杂度分析 上述算法的时间复杂度主要取决于递归调用次数以及每次递归中的操作数量。由于需要遍历所有的可能组合并对其进行剪枝处理,因此时间复杂度难以精确计算,但通常可以表示为 \(O(2^n)\),其中 \(n\) 是输入数组的长度[^1]。空间复杂度由递归栈决定,最坏情况下为 \(O(n)\)[^2]。 --- ### 动态规划方法的可能性探讨 虽然动态规划常用于解决子集求和类问题,但在本题中并不适用,因为题目要求输出具体的组合而非仅仅判断是否存在满足条件的集合。因此,采用回溯法更为合适[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值