1. 程式人生 > 其它 >Latex用MathType編寫公式及一些論文常用的方法

Latex用MathType編寫公式及一些論文常用的方法

☆☆☆程式碼: 排序剪枝後效率更高 ~

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();

        Arrays.sort(candidates);
        dfs(candidates,0, target, new ArrayList<>(), res);

//        Arrays.sort(candidates);
// dfs1(candidates, 0, target, new ArrayList<>(), res); return res; } // 難點是如何去除重複的組合 //(每次i從0開始搜尋) 去重前 : [ [2,2,2,2],[2,3,3],[3,2,3],[3,3,2],[3,5],[5,3] ] //(每次 i 從index開始搜尋)去重後 : [ [2,2,2,2],[2,3,3],[3,5] ] // 優化前: 4ms // 優化後(排序+剪枝):2ms private void dfs(int[] nums,int
start, int target, List<Integer> list, List<List<Integer>> res) { // if (target < 0) return; // 排序剪枝後不需要加,因為小於0的部分被剪枝 if (target == 0) { res.add(new ArrayList<>(list)); return; } for (int i = start; i < nums.length; i++) {
if (target < nums[i]) break; // 排序後剪枝,後面全是大於target的,直接跳出 list.add(nums[i]); // 由於每一個元素可以重複使用,下一輪搜尋的起點依然是 i dfs(nums, i,target - nums[i], list, res); list.remove(list.size() - 1); } } /** * 回溯寫法2:做選擇 * 優化前:4ms * 優化(排序+剪枝):2ms */ private void dfs1(int[] nums, int index, int target, List<Integer> list, List<List<Integer>> res) { if (index == nums.length) return; if (target == 0) { res.add(new ArrayList<>(list)); return; } // if (target < 0) return; // 優化前剪枝 if (target < nums[index]) return; //優化後剪枝 candidates排序後,target小於當前的值就不用往後算了 list.add(nums[index]); dfs1(nums, index, target - nums[index], list, res); list.remove(list.size() - 1); dfs1(nums, index + 1, target, list, res); } }