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

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

377. Combination Sum IV -Medium

2019-11-14 11:40:14
字體:
來源:轉載
供稿:網友

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]
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 托克逊县| 青田县| 龙泉市| 永年县| 册亨县| 丽江市| 安乡县| 沾益县| 锡林浩特市| 佛山市| 弥渡县| 乌审旗| 上高县| 台州市| 黄浦区| 辛集市| 杭州市| 深水埗区| 横山县| 奉新县| 五原县| 涟源市| 丹阳市| 乡城县| 桓仁| 肥东县| 忻城县| 兴隆县| 西丰县| 安徽省| 客服| 兴义市| 宁阳县| 扶余县| 孙吴县| 太原市| 太原市| 贺兰县| 寿阳县| 建昌县| 苗栗市|