• 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
  • 相关阅读:
    设计模式之创建型模式
    Django Admin的简单使用
    单例模式
    自定义异步IO模块
    ps 处理gif
    安装vmware tools问题
    ppt图片在word中不能正常显示,只显示为矩形框的解决方法
    没有注册类别的一种解决方法
    VS2008安装“Visual Studio Web 创作组件”安装失败的解决方法
    Ubuntu重装VMwareTools
  • 原文地址:https://www.cnblogs.com/mr-stn/p/9220618.html
Copyright © 2020-2023  润新知