Combination Sum IV(LeetCode)

本文探讨了一道典型的组合求和问题,给出了两种解决方案。首先介绍了使用递归深度优先搜索的方法,但由于时间和空间复杂度过高而不可行。随后提出了一种基于动态规划的优化方案,通过构建一个动态规划数组来高效地计算所有可能的组合数量。

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

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example:

nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?

What limitation we need to add to the question to allow negative numbers?

给你一个数组,全是正数,没有重复的,找到所有和为给定数的组合,顺序不一样的算不同的组合,返回个数。

思路:1.会惯性思维,想用递归+dfs,实现了,发现内存超了,时间超了。

class Solution {
public:
	int combinationSum4(vector<int>& nums, int target) {
		vector<vector<int> > ans;
		vector<int> cur;
		if (nums.size() == 0 || target < 0)
			return 0;
		sort(nums.begin(), nums.end());
		dfs(nums, target, 0, ans, cur);
		return ans.size();
 	}
	void dfs(vector<int>& nums, int target, int start, vector<vector<int> >& ans, vector<int>& cur) {
		if (target < 0) return;
		if (target == 0)
			ans.push_back(cur);
		for (int i = 0; i < nums.size(); i++) {
			cur.push_back(nums[i]);
			dfs(nums, target-nums[i], 0, ans, cur);
			cur.pop_back();
		}
	}
};
2.因为这题只要返回组合的个数就可以了,所以可以使用背包的方法,用一个数组dp,dp[i]存放和为i的组合有多少个,这样dp[x]=所有dp[x-num]的和,num是给定数组里的元素,形成一个类似多米诺骨牌的效果,有前面的计算结果得到后面一个的结果。
class Solution {
public:
	int combinationSum4(vector<int>& nums, int target) {
		vector<int> dp(target + 1);//背包
		dp[0] = 1;//初始条件为1
		sort(nums.begin(), nums.end());
		for (int i = 1; i <= target;i++) {
			for (auto num : nums) {
				if (i < num) break;
				dp[i] += dp[i - num];
			}
		}
		return dp.back();
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值