国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

377. Combination Sum IV -Medium

2019-11-14 12:34:41
字體:
來源:轉載
供稿:網友

Question

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.

Solution

這道題可以用dfs+記憶化解決,但是我這里用dp來解決。思路為:既然target是數組中數字的組合,target - nums[i]和target有一定的關系。假設dp[i]為數組的元素加起來為i的方法個數,遞推關系式為:dp[target] = sum(dp[target - nums[i]]),即把加上每個nums的元素到達target的方法數(dp[target - nums[i]])相加的總和就是數組元素加起來為target的方法總數

class Solution(object): def combinationSum4(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ dp = [1] + [0] * target for index in range(target + 1): # 把每個target - nums[i]的方法數相加 for n in nums: # nums的當前元素要小于target,否則拋棄該元素 if n <= index: dp[index] += dp[index - n] return dp[target]
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 神池县| 吉木萨尔县| 桐乡市| 湘阴县| 长沙市| 宁晋县| 兰考县| 全州县| 崇礼县| 洛隆县| 迁西县| 蓬溪县| 吴江市| 衡水市| 嘉善县| 嘉兴市| 梨树县| 木兰县| 漾濞| 库尔勒市| 安达市| 隆子县| 河曲县| 黎川县| 五寨县| 金溪县| 威远县| 剑阁县| 长宁县| 台中市| 商河县| 本溪市| 呼伦贝尔市| 宜昌市| 滁州市| 漳平市| 仙桃市| 元朗区| 江孜县| 防城港市| 苏尼特右旗|