Try   HackMD

Leetcode 377. Combination Sum IV

tags: Leetcode(JAVA)

題目 : https://leetcode.com/problems/combination-sum-iv/

想法 :

​​​​無窮背包問題,只是這次裡外迴圈要對調,類似爬樓梯DP。
​​​​因為每一個Value都可以從不同的Weight走上去,代表著順序的不同。

時間複雜度 : O(n*m)。

程式碼 : (JAVA)

class Solution {
    public int combinationSum4(int[] nums, int target) {
        int l=nums.length;
        int[] dp=new int[1010];
        
        dp[0]=1;
        for(int i=0 ; i<=target ; i++){
            for(int j=0 ; j<l ; j++){
                if(i-nums[j] >= 0){
                    dp[i]+=dp[i-nums[j]];
                }                
            }
        }
        
        return dp[target];
    }
}