【leetcode 39】 Combination Sum 組合總數

 題目

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]
]

解題思路

本題要求給出一個數組和一個目標的值,在數組中選擇n個數字,得到所有可以相加等於目標值得情況,且結果的集合中不可以存在重複的組合。

這很顯然是要對所有的情況進行遍歷,在遍歷的過程中,得到所有符合條件的集合放入到結果集中。本人對於遞歸相關的解法掌握的不好,所以參考率前人提交的解法,選出了兩種解法和大家分享

代碼實現

1、遞歸方式

public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
    	Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        getResult(result, new ArrayList<Integer>(), candidates, target, 0);
        
        return result;
    }
    
    private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
    	if(target > 0){
    		for(int i = start; i < candidates.length && target >= candidates[i]; i++){
    			cur.add(candidates[i]);
    			getResult(result, cur, candidates, target - candidates[i], i);
    			cur.remove(cur.size() - 1);
    		}//for
    	}//if
    	else if(target == 0 ){
    		result.add(new ArrayList<Integer>(cur));
    	}//else if
    }
}

2、非遞歸方式

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    Arrays.sort(candidates);
    int i=0, size = candidates.length, sum=0;
    Stack<Integer> combi = new Stack<>(), indices = new Stack<>();
    List<List<Integer>> result = new ArrayList<>();
    while (i < size) {
    	if (sum + candidates[i]>= target) {
    		if (sum + candidates[i] == target) {
    			combi.push(candidates[i]);
    			result.add(new ArrayList<>(combi));
    			combi.pop();
    		}
    		// indices stack and combination stack should have the same size all the time
    		if (!indices.empty()){
    			sum -= combi.pop();
    			i = indices.pop();
    			while (i == size-1 && !indices.empty()) {
    				i = indices.pop();
    				sum -= combi.pop();
    				
    			}
    		}
    		i++;
    	} else {
    		combi.push(candidates[i]);
    		sum +=candidates[i];
    		indices.push(i);
    	}
    }
    return result;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章