Combination Sum IV

Source: Internet
Author: User

Given an integer array with all positive numbers and no duplicates, find the number of possible combinations this add up t o a positive integer target.

Example:

nums = [1, 2, 3]target7.

Follow up:
What if negative numbers is allowed in the given array?
How does does it change the problem?
What limitation we need to add to the question to allow negative numbers?

Analyse:for every number I from 1 ... target, we check the numbers num in nums, if I >= num, we seperate i to num an D I-num, and compute how many ways i-num is consisted. That's to say, dp[i] + = Dp[i-num].

Runtime:4ms.

1 classSolution {2  Public:3     intCOMBINATIONSUM4 (vector<int>& Nums,inttarget) {4vector<int> dp (target +1,0);5         6dp[0] =1;7          for(inti =1; I <= target; i++) {8              for(Auto num:nums) {9                 if(I >=num)TenDp[i] + = dp[i-num]; One             } A         } -         returnDp[target]; -     } the};

Combination Sum IV

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.