zoukankan      html  css  js  c++  java
  • leetcode 377. Combination Sum IV

    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?

    Credits:
    Special thanks to @pbrother for adding this problem and creating all test cases.

    题目大意:找出数组中能组合成目标数的组合, 每个数字的使用次数不限

    思路:用dp算法:从底到顶的计算,依次算出组合成1,2,3,4有多少种组合;

      以上面的例子为例:【1,2,3】 target=4;

      设置一个数组dp()来保存结果, dp[i]表示和为i的组合个数, 初始条件是dp[0]=1;

           遍历数组如果当前的数num[j]比target小那么,只需知道 dp[target-num[j]] 就行了。相当于在和为target-nums[j]的组合后面构成了新的组合,满足和为target, 把所有满足nums[j]<target的dp[target-nums[j]]加起来就得到了target的组合; 

           dp的代码简洁,关键在于找到关系式

     1 class Solution {
     2 public:
     3     int combinationSum4(vector<int>& nums, int target) {
     4         int n=nums.size(),i,j;
     5         int dp[target+1]={0};
     6         dp[0]=1;
     7         for(i=1;i<=target;i++){
     8             for(j=0;j<n;j++){
     9                 if(i >= nums[j])
    10                     dp[i] += dp[i-nums[j]];
    11             }
    12         }
    13         return dp[target];
    14     }
    15 };
    有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
  • 相关阅读:
    AJAX---发送GET请求并传递参数
    AJAX---遵循http协议
    AJAX---onreadystatechange事件中获取相应内容和readystate状态
    AJAX---发送请求
    AJAX---简介
    AJAX---学习roadmap
    jQuery---jquery.ui实现新闻模块
    jQuery---jquery.color.js和jquery.lazyload.js的使用
    jQuery---jQuery插件
    通过JavaScript调用SOAP终结点执行实体消息
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9220618.html
Copyright © 2011-2022 走看看