Combination Sum IV
早上起来看到朋友微信说出新题了,于是打开leetcode 看了一下,原来又是Combination Sum。 打开之后果断用了之前三个Combination Sum 用到的 Backtracking, then submit, TIME LIMIT EXCEEDED, XD. 看了下tags,原来是用DP,于是写了个DP的sulotion
状态转移方程: combinationSum4(x): f(x)
f(target) = f(target - nums[0]) + f(target - nums[1]) + ... + f(target - nums.back())
附上之前三个combinationSum的题,没有做前三个的可以先做一下前三个
Combination Sum
Combination Sum II
Combination Sum III
int combinationSum4(vector<int>& nums, int target) {
vector<int> res(target + 1, 0);
res[0] = 1;
for (int i = 1; i <= target; i++)
for (int n: nums)
if (i >= n)
res[i] += res[i - n];
return res.back();
}
网友评论