1. 程式人生 > 其它 >Combination Sum 組合數求和-Leetcode

Combination Sum 組合數求和-Leetcode

原題:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a
    1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7,  A solution set is:  [7] [2, 2, 3]


題意是找到所有加起來和為target值的組合,候選數可以重複使用。這明顯是一道利用回溯的題目,可以想象成深度搜索。

以題目給出的【2,3,6,7】為例。一棵樹根節點有四個子節點(2,3,6,7)。每個子節點下又有不小於本子節點的所有子節點。

比如子節點2下面仍然有(2,3,6,7)四個子節點,子節點3下面有(3,6,7)三個子節點。我們就在這樣一棵樹上進行深搜,返回的條件是經過的節點的和為target。停止的條件是返回到根節點且無下一個子節點可用。

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        solve(candidates,0,target,new LinkedList<Integer>());
        return ans;
    }
    private List<List<Integer>> ans=new LinkedList<>();
    private  void solve(int[] candidates,int start,int target,LinkedList<Integer> current){
        if (target==0){
            ans.add(copy(current));
            return;
        }
        if (target<candidates[start]){
            return;
        }
        else {
            for (int iterator=start;iterator<candidates.length;iterator++){
                if (candidates[iterator]>target){
                    break;
                }
                current.add(candidates[iterator]);
                solve(candidates, iterator, target - candidates[iterator], current);
                current.pollLast();
            }
            return;
        }
    }
    private LinkedList<Integer> copy(LinkedList<Integer> source){
        LinkedList<Integer> dest=new LinkedList<>();
        for (int i:source){
            dest.add(i);
        }
        return dest;
    }
}

另一個效率更高的演算法,逆向思維。

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        return combinationSum(candidates, target, 0);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target, int start) {

        List<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(candidates);
        for (int i = start; i < candidates.length; i++) {
            if (candidates[i] <target) {
                for (List<Integer> ar : combinationSum(candidates, target - candidates[i], i)) {
                    ar.add(0, candidates[i]);
                    res.add(ar);
                }
            } else if (candidates[i] == target) {
                List<Integer> lst = new ArrayList<>();
                lst.add(candidates[i]);
                res.add(lst);
            } else
                break;
        }
        return res;
    }
}