377. Combination Sum IV

Description

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.

Solution

Recursion with memo

由于本题是顺序相关的,其实应该是permutation而非combination,用memo以避免重复计算子问题。

用DP也可以解。

class Solution {
    public int combinationSum4(int[] nums, int target) {
        return combinationSum4Recur(nums, target, new HashMap<>());
    }
    
    public int combinationSum4Recur(int[] nums, int target, Map<Integer, Integer> map) {
        if (target == 0) {
            return 1;
        }
        if (target < 0) {
            return 0;
        }
        if (map.containsKey(target)) {
            return map.get(target);
        }
        
        int count = 0;
        
        for (int n : nums) {
            count += combinationSum4Recur(nums, target - n, map);
        }
        
        map.put(target, count);
        return count;
    }
}

Follow-up

如果array中有负数,则需要给定一个combination maximum length,用来终止递归。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 妳知道什麽叫“不作不死”嗎? 雖然說,既然來到這個世界,誰都沒打算活著回去。 但我相信,沒有誰願意匆匆地來,匆匆地...
    大宇Drizzles阅读 528评论 1 1
  • 6月是考试月,雨水伴随着各类考试渗透祖国大地。而我做为离开高校已8年的老社会人士,没想到还能参加理财培训班...
    囡囡945阅读 230评论 0 0
  • 8.7-8.22,一段持续了半个月的旅程。 一次旅行,一次收获。 台湾和大陆,隔着浅浅的一道海峡,却隔了太多太多。...
    满月成玦阅读 230评论 0 2
  • 当我无所事事、自由散漫的时候,吃饭是一件很重要的事,得换换口味,得吃肉,得好吃。 当我心里装着事,很正经地忙碌时,...
    敏而好学happy阅读 228评论 5 1