Combination Sum--LeetCode

本文介绍了一种用于解决组合数问题的算法,通过递归的方式在候选数集中寻找所有可能的组合,使得这些组合之和等于目标数值。算法确保了组合的唯一性,并且元素按非降序排列。通过实例演示了如何使用该算法,以及在求解过程中需要注意的关键点,包括路径搜索和避免重复解的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:求组合数

#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
 Given a set of candidate numbers (C) and a target number (T), 
 find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

    All numbers (including target) will be positive integers.
    Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7, 
A solution set is: 
[7] 
[2, 2, 3] 
*/

void Combination_helper(vector<int>& vec,int begin,int target,int& cur,vector<int>& path)
{
	
	if(begin >=vec.size())
		return ;
		
	
	cur += vec[begin];
	path.push_back(vec[begin]);
	if(cur == target)
	{
		for(int i=0;i<path.size();i++)
			cout<<path[i]<<endl;
		cout<<"=========="<<endl;
	}
	Combination_helper(vec,begin+1,target,cur,path);
	path.pop_back();
	cur -= vec[begin];
	Combination_helper(vec,begin+1,target,cur,path);	
}

void Combination(vector<int>& vec,int target)
{
	vector<int> path;
	int cur = 0;
	if(vec.size() == 0)
		return ;
	Combination_helper(vec,0,target,cur,path);
}

int main()
{
	
	vector<int> path;
	int array[]={2,5,6,7};
	int cur =0;
	vector<int> vec(array,array+sizeof(array)/sizeof(int)); 
	Combination(vec,7);
	return 0;
}

这里需要注意的地方有两点,第一

if(cur == target)
	{
		for(int i=0;i<path.size();i++)
			cout<<path[i]<<endl;
		cout<<"=========="<<endl;
	}
else
{ Combination_helper(vec,begin+1,target,cur,path);
	path.pop_back();
	cur -= vec[begin];
	Combination_helper(vec,begin+1,target,cur,path);	
}
不能写成这样,如果有一符合条件,紧接着有一个符合条件 那么不能得以实现。第二个是打印的地方不能return
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值