LeetCode-combination-sum (JAVA)

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

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

Note:

All numbers (including target) will be positive integers. The solution
set must not contain duplicate combinations.
Example 1:

Input: candidates = [2,3,6,7], target = 7, A solution set is: [ [7],
[2,2,3] ]
Example 2:

Input: candidates = [2,3,5], target = 8, A solution set is: [
[2,2,2,2], [2,3,3], [3,5] ]

根據數組中的字數,求取加和爲目標數,數組中數字出現次數可大於1.

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        return combinationSum1(candidates, target, 0);
        
    }
    public List<List<Integer>> combinationSum1(int[] candidates, int target, int begin) {
        int n =candidates.length;
        List<List<Integer>> ret = new ArrayList();
        for(int i = begin; i < n; i++){
            int num = candidates[i];
            int c = target / num;
            if(c == 0) {
                return ret;
            }
            for (int s = 1; s < c + 1; s++) {
                List<List<Integer>> temp = combinationSum1(candidates, target - num * s, 1 + i);
                if(temp.size() > 0) {
                    for(int j = 0 ;j < temp.size(); j++) {
                        List<Integer> com = temp.get(j);
                        for(int k = 1; k < s + 1; k++) {
                           com.add(num); 
                        }
                         ret.add(com);
                    }
                } else if(num * s == target){
                    List<Integer> com = new ArrayList();
                    for(int k = 1; k < s + 1; k++) {
                        com.add(num); 
                    }
                    ret.add(com);
                }
            }
        }
        return ret;
    } 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章