【LeetCode】 377. Combination Sum IV
2017-01-11 01:25
197 查看
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:
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?
public class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
Arrays.fill(dp, -1);
dp[0] = 1;
return helper(nums, dp, target);
}
private int helper(int[] nums, int[] dp, int target) {
if (dp[target] != -1) {
return dp[target];
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (target >= nums[i]) {
res += helper(nums, dp, target - nums[i]);
}
}
dp[target] = res;
return res;
}
}
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?
public class Solution {
public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
Arrays.fill(dp, -1);
dp[0] = 1;
return helper(nums, dp, target);
}
private int helper(int[] nums, int[] dp, int target) {
if (dp[target] != -1) {
return dp[target];
}
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (target >= nums[i]) {
res += helper(nums, dp, target - nums[i]);
}
}
dp[target] = res;
return res;
}
}
相关文章推荐
- (写公式,解方程)LightOJ - 1062
- 2.输入系统驱动(3)-input内核级驱动设计
- iCCP: known incorrect sRGB profile
- Codeforces Round #386 (Div. 2) D. Green and Black Tea 数论+贪心
- 2.输入系统驱动(2)-input系统框架层分析
- OSI模型与TCP/IP模型
- 2.输入系统驱动(1)-input应用程序设计
- java内存溢出示例(堆溢出、栈溢出)
- wxPython开发总结---将Python源代码打包成exe可执行文件
- shader渲染管线
- ionicCSS04_卡片
- 在云服务器上部署项目(上)
- 基于FFmpeg 和 OpenGL 的音视频合成+过渡特效【C++】
- tomcat 7内存调大也起不来
- 分布式架构的演变
- JavaFX如何实现模态窗口
- 统一的初始化方式
- Mysql导入数据库的方法
- git快速上手教程
- Spring 框架的搭建及测试