|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=377 lang=golang |
| 3 | + * |
| 4 | + * [377] 组合总和 Ⅳ |
| 5 | + * |
| 6 | + * https://leetcode.cn/problems/combination-sum-iv/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (52.74%) |
| 10 | + * Likes: 908 |
| 11 | + * Dislikes: 0 |
| 12 | + * Total Accepted: 166.7K |
| 13 | + * Total Submissions: 316K |
| 14 | + * Testcase Example: '[1,2,3]\n4' |
| 15 | + * |
| 16 | + * 给你一个由 不同 整数组成的数组 nums ,和一个目标整数 target 。请你从 nums 中找出并返回总和为 target 的元素组合的个数。 |
| 17 | + * |
| 18 | + * 题目数据保证答案符合 32 位整数范围。 |
| 19 | + * |
| 20 | + * |
| 21 | + * |
| 22 | + * 示例 1: |
| 23 | + * |
| 24 | + * |
| 25 | + * 输入:nums = [1,2,3], target = 4 |
| 26 | + * 输出:7 |
| 27 | + * 解释: |
| 28 | + * 所有可能的组合为: |
| 29 | + * (1, 1, 1, 1) |
| 30 | + * (1, 1, 2) |
| 31 | + * (1, 2, 1) |
| 32 | + * (1, 3) |
| 33 | + * (2, 1, 1) |
| 34 | + * (2, 2) |
| 35 | + * (3, 1) |
| 36 | + * 请注意,顺序不同的序列被视作不同的组合。 |
| 37 | + * |
| 38 | + * |
| 39 | + * 示例 2: |
| 40 | + * |
| 41 | + * |
| 42 | + * 输入:nums = [9], target = 3 |
| 43 | + * 输出:0 |
| 44 | + * |
| 45 | + * |
| 46 | + * |
| 47 | + * |
| 48 | + * 提示: |
| 49 | + * |
| 50 | + * |
| 51 | + * 1 |
| 52 | + * 1 |
| 53 | + * nums 中的所有元素 互不相同 |
| 54 | + * 1 |
| 55 | + * |
| 56 | + * |
| 57 | + * |
| 58 | + * |
| 59 | + * 进阶:如果给定的数组中含有负数会发生什么?问题会产生何种变化?如果允许负数出现,需要向题目中添加哪些限制条件? |
| 60 | + * |
| 61 | + */ |
| 62 | +package jzoffer |
| 63 | + |
| 64 | +// @lc code=start |
| 65 | +// 直接用回溯会超时,使用map存储中间结果或者使用dp解答 |
| 66 | +func combinationSum4Backtrack(nums []int, target int) (res int) { |
| 67 | + mRes := make(map[int]int) |
| 68 | + var dfs func(cancidate []int, left int) int |
| 69 | + dfs = func(cancidate []int, left int) int { |
| 70 | + if left < 0 { |
| 71 | + return 0 |
| 72 | + } |
| 73 | + if left == 0 { |
| 74 | + mRes[left] = 1 |
| 75 | + return 1 |
| 76 | + } |
| 77 | + num := 0 |
| 78 | + for _, v := range nums { |
| 79 | + if left-v < 0 { |
| 80 | + continue |
| 81 | + } |
| 82 | + if n, ok := mRes[left-v]; ok { |
| 83 | + num += n |
| 84 | + continue |
| 85 | + } |
| 86 | + n := dfs(cancidate, left-v) |
| 87 | + mRes[left-v] = n |
| 88 | + num += n |
| 89 | + } |
| 90 | + return num |
| 91 | + } |
| 92 | + res += dfs(nums, target) |
| 93 | + return |
| 94 | +} |
| 95 | + |
| 96 | +func combinationSum4(nums []int, target int) (res int) { |
| 97 | + mRes := make(map[int]int) |
| 98 | + mRes[0] = 1 |
| 99 | + for i := 1; i <= target; i++ { |
| 100 | + for _, v := range nums { |
| 101 | + if i-v >= 0 { |
| 102 | + mRes[i] += mRes[i-v] |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | + return mRes[target] |
| 107 | +} |
| 108 | + |
| 109 | +// @lc code=end |
0 commit comments