Combination Sum

Combination Sum

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.code

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 (a1, a2, … , ak) must be in non-descending order. (ie,
a1 ≤ a2 ≤ … ≤ ak). The solution set must not contain duplicate
combinations.rem

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

思路: 把target number 傳入, 每次加入一個數字,就把target number 減去這個數字遞歸。 當target number == 0 時,說明此時list中的數字的和爲target number。 就能夠將這組數字加入list裏面。 注意能夠重複加數字, 因此每次遞歸傳的index就是i。it

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(candidates);
        int sum = target;
        helper(result,list, sum,candidates,0);
        return result;
    }
    private void helper(List<List<Integer>> result, List<Integer> list,int sum, int[] candidates,int index) {
        if (sum == 0) {
            result.add(new ArrayList<Integer>(list));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (sum < 0) {
                break;
            }
            list.add(candidates[i]);
            helper(result,list, sum - candidates[i], candidates,i);
            list.remove(list.size() - 1);
        }
    }
}
相關文章
相關標籤/搜索