Combination Sum IV问题及解法

来源:互联网 发布:淘宝域名助手下载 编辑:程序博客网 时间:2024/05/21 15:46

问题描述:

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.

示例:

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.

问题分析:

我们设置dp[i]为值为i是的组合数,对与1.到target的值,dp[i] += dp[i - nums[j]],j = 0...,nums.size() - 1.


过程详见代码:

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


原创粉丝点击