博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Combination Sum IV && Summary: The Key to Solve DP
阅读量:4349 次
发布时间:2019-06-07

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

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?

DP 解法: the key to solve DP problem is to think about how to create overlap, how to re-solve subproblems(怎么制造复用)

Bottom up dp:

1 public class Solution { 2     public int combinationSum4(int[] nums, int target) { 3         if (nums==null || nums.length==0) return 0; 4         Arrays.sort(nums); 5         int[] dp = new int[target+1]; 6         dp[0] = 1; 7         for (int i=1; i<=target; i++) { 8             for (int j=0; j

Better Solution(Bottom-up)不sort也成:

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

 

 

Follow up:

I think if there are negative numbers in the array, we must add a requirement that each number is only used one time, or either positive number or negative number should be used only one time, otherwise there would be infinite possible combinations.

For example, we are given:
{1, -1}, target = 1,
it's obvious to see as long as we choose n 1s and (n-1) -1s, it always sums up to 1, n can be any value >= 1.

转载于:https://www.cnblogs.com/EdwardLiu/p/6108838.html

你可能感兴趣的文章
Ubuntu菜鸟入门(五)—— 一些编程相关工具
查看>>
valgrind检测linux程序内存泄露
查看>>
“==”运算符与equals()
查看>>
单工、半双工和全双工的定义
查看>>
Hdu【线段树】基础题.cpp
查看>>
时钟系统
查看>>
BiTree
查看>>
5个基于HTML5的加载动画推荐
查看>>
水平权限漏洞的修复方案
查看>>
静态链接与动态链接的区别
查看>>
如何使用mysql
查看>>
敏捷开发中软件测试团队的职责和产出是什么?
查看>>
在mvc3中使用ffmpeg对上传视频进行截图和转换格式
查看>>
python的字符串内建函数
查看>>
Spring - DI
查看>>
微软自己的官网介绍 SSL 参数相关
查看>>
Composite UI Application Block (CAB) 概念和术语
查看>>
ajax跨域,携带cookie
查看>>
阶段3 2.Spring_02.程序间耦合_7 分析工厂模式中的问题并改造
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_2 spring中的Ioc前期准备
查看>>