leetcode題目
組合總和IV -- leetcode 377
題目描述
給定一個由正整數組成且不存在重複數字的數組,找出和爲給定目標正整數的組合的個數。
示例:
nums = [1, 2, 4]
target = 4
所有可能的組合爲:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(2, 1, 1)
(2, 2)
(4)
請注意,順序不同的序列被視作不同的組合。
因此輸出爲 7。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/combination-sum-iv
思路
* 1、動態規劃
* 2、求target爲n 相當於dp[i]表示target爲i的結果個數
* 遍歷nums數組,如果i>=x,dp[i]+=dp[i-x],因爲
* dp[3]=dp[2]+1或dp[1]+2或dp[0]+3
*
* 再舉個例子
* dp[i]=dp[i-nums[0]]+dp[i-nums[1]]+dp[i=nums[2]]+...
* 比如nums=[1,3,4],target=7;
* dp[7]=dp[6]+dp[4]+dp[3]
* 其實就是說7的組合數可以由三部分組成,1和dp[6],3和dp[4],4和dp[3];
代碼
package com.leetcode.array;
/**
* 題目:
* 組合總和IV -- leetcode 377
*
* 題目描述:
*
給定一個由正整數組成且不存在重複數字的數組,找出和爲給定目標正整數的組合的個數。
示例:
nums = [1, 2, 4]
target = 4
所有可能的組合爲:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(2, 1, 1)
(2, 2)
(4)
請注意,順序不同的序列被視作不同的組合。
因此輸出爲 7。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/combination-sum-iv
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
*/
public class CombinationSumIV {
/**
* 思路:
* 1、動態規劃
* 2、求target爲n 相當於dp[i]表示target爲i的結果個數
* 遍歷nums數組,如果i>=x,dp[i]+=dp[i-x],因爲
* dp[3]=dp[2]+1或dp[1]+2或dp[0]+3
*
* 再舉個例子
* dp[i]=dp[i-nums[0]]+dp[i-nums[1]]+dp[i=nums[2]]+...
* 比如nums=[1,3,4],target=7;
* dp[7]=dp[6]+dp[4]+dp[3]
* 其實就是說7的組合數可以由三部分組成,1和dp[6],3和dp[4],4和dp[3];
*/
public int combinationSum4(int[] nums, int target) {
if (nums == null) {
return 0;
}
int[] dp = new int[target+1];
dp[0] = 1;
for (int i=1; i<=target; i++) {
for (int x : nums) {
if (i > x) {
dp[i] += dp[i-x];
}
}
}
return dp[target];
}
}