动态规划——377. Combination Sum IV[Medium]

来源:互联网 发布:php include() 编辑:程序博客网 时间:2024/05/21 22:29

题目描述

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 = 4The 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.

给定一个数组和一个指定的和,问能有多少种方式选取数组数字相加得到这个 和。


解题思路

1)数组many[i]表示 和 为 i 时的总方式数

2)遍历给定数组nums,many[i]+= many[i - nums[j]]

3)返回many[target]

其实就是考虑从i - nums[j]到 i 有几种走法,和之前的爬楼梯类似。


注意双重循环,遍历many在外层,因为many[i]+= many[i - nums[j]],则many[i - nums[j]]要先于many[i]求出来,

放在内层可能会对many[i - nums[j]]多次更新导致结果不准确


代码如下

class Solution {public:    int combinationSum4(vector<int>& nums, int target) {vector<int> many(target+1, 0);many[0] = 1;for (int j = 1; j <= target; j++) {    for (int i = 0; i < nums.size(); i++) {if (j - nums[i] < 0) continue;many[j] += many[j - nums[i]];}}return many[target];}};