在leetcode上刷到這個題時,起初會感覺這個題不是很難,但做下去後會發現這個題有點複雜如果用暴力法就是幾個for迴圈,其時間複雜度會非常大,所以在優化,提取後,我採用了遞迴法,因為遞迴呼叫後,相當於之後的已經找到了,只需要找到當前的就可以了,就不是很複雜;
這是我的遞迴函式:
主函式:private static void find(list> listall, listlist, int candidates, int target, int num)
}if(targetnum && candidates[i]==candidates[i-1]) continue;//這是我之後的判斷,這時間複雜度降低了好多
listtmp=new arraylist<>(list);
tmp.add(candidates[i]);
find(listall,tmp,candidates,target-candidates[i],i+1);
} }
public list> combinationsum2(int candidates, int target)
組合總和II
給定乙個無重複元素的陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的數字可以無限制重複被選取。說明 所有數字 包括 target 都是正整數。解集不能包含重複的組合。示例 1 輸入 candid...
組合總和 II
給定乙個陣列 candidates 和乙個目標數 target 找出 candidates 中所有可以使數字和為 target 的組合。candidates 中的每個數字在每個組合中只能使用一次。說明 所有數字 包括目標數 都是正整數。解集不能包含重複的組合。示例 1 輸入 candidates 1...
LeetCode 組合總和
給定乙個由正整數組成且不存在重複數字的陣列,找出和為給定目標正整數的組合的個數。示例 nums 1,2,3 target 4 所有可能的組合為 1,1,1,1 1,1,2 1,2,1 1,3 2,1,1 2,2 3,1 請注意,順序不同的序列被視作不同的組合。因此輸出為 7。高階 如果給定的陣列中含...