博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
377. Combination Sum IV
阅读量:4510 次
发布时间:2019-06-08

本文共 1559 字,大约阅读时间需要 5 分钟。

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 = 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.

 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?

题目含义:给定多个正整数且没有重复,从中挑选任意个数字(可以重复)使其加起来等于给定目标值target

思路:

 dp[i]表示总和为i的情况数,假设当前整数值等于n(n<i),如果我们知道了 dp[i-n] 的情况数,因为 dp[i-n] 的每一种情况加n都等于dp[i],所以说dp[i-n]和dp[i]的情况数相同。

 每获取一个整数n,都会给了dp[i]添加dp[i-n]种情况,所以公式为dp[i] = dp[i] + dp[i-n]

例如:

 当前元素n等于1时,dp[9] = dp[9] + dp[9-1]
          dp[8] = dp[8] + dp[8-1]
           ...
          dp[1] = dp[1] + dp[1-1]
 当前元素n等于2时,dp[9] = dp[9] + dp[9-2]
             dp[8] = dp[8] + dp[8-2]
           ...
             dp[2] = dp[2] + dp[2-2]
 当前元素n等于3时,dp[9] = dp[9] + dp[9-3]
             dp[8] = dp[8] + dp[8-3]
           ...
             dp[3] = dp[3] + dp[3-3]

1     public int combinationSum4(int[] nums, int target) {                   2         int[] dp=new int[target+1]; 3         dp[0]=1; 4         for(int i=1;i<=target;i++) 5         { 6             for (int num:nums) 7             { 8                 if(i>=num) dp[i]=dp[i]+dp[i-num]; 9             }10         }11         return dp[target];12     }

 

 类似题目: 

请注意:本题目选取的数字可以多次重复,而题目494中的数字不可重复选择

转载于:https://www.cnblogs.com/wzj4858/p/7694733.html

你可能感兴趣的文章
POJ 2311 Cutting Game(二维SG+Multi-Nim)
查看>>
1978 Fibonacci数列 3
查看>>
1225 八数码难题
查看>>
C#控件的闪烁问题解决方法总结
查看>>
js 冒泡事件与解决冒泡事件
查看>>
2018-2019赛季多校联合新生训练赛第七场(2018/12/16)补题题解
查看>>
后台全选功能以及数据的提交方法
查看>>
Android 动画效果 及 自定义动画
查看>>
const与#define相比有什么不同?
查看>>
Eclipse4.7 SpringIDE插件的安装
查看>>
C#面向对象基础
查看>>
Jquery页面加载效果
查看>>
ios对new Date() 的兼容问题
查看>>
Spark发展现状与战线
查看>>
Charles常用设置
查看>>
filebeat
查看>>
如何在Bitmap中画图?(MFC)
查看>>
Windows 用来定位 DLL 的搜索路径
查看>>
常见的游戏设计技术
查看>>
Backbone 学习笔记五
查看>>