LeetCode[377] Combination Sum IV

来源:互联网 发布:vscode 代码提示 编辑:程序博客网 时间:2024/06/05 21:52

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?

动态规划。对于 sum = 0 的情况,只有一种可能,就是什么都不放。如果我们能求出 sum = target - i 有多少种情况(记为x),那么那么最后一步就只有一个选择:把 i 放进去。于是经过 target - i 到达 target 就有 x 种情况。所以我们只需要计算出到达 1~target-1 分别有多少种情况,target再各取所需即可

对于 folow up 中的可以有负数的情况,如果不限制每个元素用的次数,就有可能有无数种情况。

class Solution {  public:      int combinationSum4(vector<int>& nums, int target) {        if (nums.size() == 0)             return 0;        vector<int> solution(target + 1, 0);        solution[0] = 1;        for (int i = 1; i <= target; i++)        {            for (int obj : nums)                if (obj <= i)                     solution[i] += solution[i - obj];        }        return solution[target];    }};  
0 0
原创粉丝点击