Combination Sum IV(LeetCode)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014485485/article/details/80959305

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();
	}
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80959305