1. 程式人生 > 實用技巧 >LeetCode 39 組合總數

LeetCode 39 組合總數

LeetCode39 組合總數

題目描述

給定一個無重複元素的陣列 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。

candidates 中的數字可以無限制重複被選取。

樣例

輸入:candidates = [2,3,6,7], target = 7,
所求解集為:
[
  [7],
  [2,2,3]
]
輸入:candidates = [2,3,5], target = 8,
所求解集為:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

演算法分析

暴力搜尋

搜尋順序問題

時間複雜度

Java程式碼

class Solution {
    static List<List<Integer>> ans = new ArrayList<List<Integer>>();

    static void dfs(int[] candidates, int target, int u, int sum, List<Integer> t){
        if(sum > target) return;

        if(u == candidates.length){
            if(sum == target){
                ans.add(new ArrayList<Integer>(t));
            }
            return;
        }

        for(int i = 0; sum + i * candidates[u] <= target; i++){
            dfs(candidates, target, u+1, sum+candidates[u]*i, t);
            t.add(candidates[u]); //
        }

        for(int i = 0; sum + i * candidates[u] <= target; i++){
            t.remove(t.size()-1);
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ans.clear();
        List<Integer> t = new ArrayList<Integer>();
        dfs(candidates,target,0,0,t);
        return ans;
    }
}