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

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

377. Combination Sum IV -Medium

2019-11-14 11:07:47
字體:
供稿:網(wǎng)友

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.

給出一個全為正整數(shù)且無重復數(shù)字的數(shù)組,找出加起來是一個正整數(shù)目標值的方法個數(shù)

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是數(shù)組中數(shù)字的組合,target - nums[i]和target有一定的關(guān)系。假設(shè)dp[i]為數(shù)組的元素加起來為i的方法個數(shù),遞推關(guān)系式為:dp[target] = sum(dp[target - nums[i]]),即把加上每個nums的元素到達target的方法數(shù)(dp[target - nums[i]])相加的總和就是數(shù)組元素加起來為target的方法總數(shù)

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]的方法數(shù)相加 for n in nums: # nums的當前元素要小于target,否則拋棄該元素 if n <= index: dp[index] += dp[index - n] return dp[target]
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 老河口市| 栖霞市| 延吉市| 台州市| 光山县| 云阳县| 皮山县| 于田县| 仁布县| 涿州市| 大化| 宝兴县| 河津市| 故城县| 曲靖市| 兴文县| 运城市| 东宁县| 波密县| 霍州市| 临沭县| 西充县| 麻栗坡县| 太保市| 富锦市| 屏边| 镇坪县| 卓尼县| 乃东县| 祁东县| 天长市| 秀山| 吉安市| 铜川市| 永和县| 如东县| 金寨县| 同江市| 长子县| 灵武市| 宁远县|