leetcode 377. 组合总和 Ⅳ

给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。

示例:

nums = [1, 2, 3]
target = 4

所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

请注意,顺序不同的序列被视作不同的组合。

因此输出为 7。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iv
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

一道典型的多阶段决策问题,通常这类问题可用解答树找到最优子结构。

 1 class Solution {
 2     Map<Integer, Integer> m = new HashMap<>();
 3 
 4     {
 5         m.put(0, 1);
 6     }
 7 
 8     public int combinationSum4(int[] nums, int target) {
 9         if (m.get(target) != null){
10             return m.get(target);
11         }
12         if (target < 0) return 0;
13         if (target == 0) return 1;
14         int sum = 0;
15         for (int i = 0; i < nums.length; i++){
16             sum += combinationSum4(nums, target-nums[i]);
17         }
18         m.put(target, sum);
19         return sum;
20     }
21 }

猜你喜欢

转载自www.cnblogs.com/yfs123456/p/11211919.html