算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 组合总和 Ⅳ,我们先来看题面:

Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.


The answer is guaranteed to fit in a 32-bit integer.


给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。题目数据保证答案符合 32 位整数范围。

示例


示例 1:
输入:nums = [1,2,3], target = 4
输出:7
解释:
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
示例 2:
输入:nums = [9], target = 3
输出:0


解题


动态规划

本题第一眼以为是dfs,但是实在想不出来下标怎么处理dp数组的意义:dp[i]代表'target = i'时的组合数目,显然此时dp数组的初始化长度为target+1。遍历规则:1 <= i <= target, ++i,target值从小到大。内层遍历是遍历nums数组。更新规则:dp[i] += dp[i-num],隐含的含义是若当前i >= num,那么可以在dp[i-num]加入num,组合为一个完整组合。边界条件:dp[0] = 1,当i == num,代表本身数字是一个组合,因此dp[0]需等于1。

class Solution {
public:

int combinationSum4(vector<int>& nums, int target) {
// dp[i]:target为i时的组合数目
vector<int> dp(target+1, 0);
dp[0] = 1;
for(int i = 1; i < target + 1;++i){
for(auto num:nums){
if(num <= i && dp[i-num] < INT_MAX - dp[i]) // 防止越界
dp[i] += dp[i - num];
}
}
return dp[target];
}
};


​LeetCode刷题实战377:组合总和 Ⅳ_数组