377. Combination Sum IV (Medium)

https://leetcode.com/problems/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.

Hints

Solutions

  • Java
class Solution {
    public int combinationSum4(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        return recursion(nums, target);
    }

    private int recursion(int[] nums, int remainTarget) {
        // 当剩余容量为 0 时,说明找到了一个方案
        if (remainTarget == 0) {
            return 1;
        }
        int rst = 0;
        // 每次 Recursion 都需要遍历整个数组
        for (int i = 0; i < nums.length; i++) {
            if (remainTarget >= nums[i]) {
                rst += recursion(nums, remainTarget - nums[i]);
            }
        }
        return rst;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-08 13:24:51

results matching ""

    No results matching ""