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

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

377. Combination Sum IV -Medium

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

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]
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 游戏| 得荣县| 会理县| 蕉岭县| 灌阳县| 禹州市| 开鲁县| 日土县| 忻州市| 连州市| 沙田区| 客服| 阿勒泰市| 南华县| 古丈县| 贺州市| 新巴尔虎右旗| 年辖:市辖区| 忻州市| 齐河县| 达尔| 乌兰浩特市| 买车| 霍山县| 贵南县| 新竹市| 嘉鱼县| 安平县| 东兴市| 高雄市| 苏尼特左旗| 山西省| 神木县| 连平县| 古交市| 高安市| 曲靖市| 安国市| 洞头县| 商都县| 宁安市|