1. 程式人生 > >從給定陣列中選取任意個數(可重複),使其和為給定值。

從給定陣列中選取任意個數(可重複),使其和為給定值。

回溯法練習:

從給定有序陣列中選取任意個數(可重複),使其和為給定值(leetcode39):

Example 1:

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

思路:回溯法的練習題。因為可以重複,注意遞迴呼叫時可以從當前位置開始取。

class Solution {
  
	List<List<Integer>> res = new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        
    	helper(candidates,target,new ArrayList<Integer>(),0);
    	return res;
    }
    
	private void helper(int[] candidates, int target, ArrayList<Integer> list,int index) {
		
		if( target == 0){
			res.add(new ArrayList<>(list));
		}
		
		for (int i = index; i < candidates.length; i++) {

			if(candidates[i] <= target){
				
				list.add(candidates[i]);
				helper(candidates, target-candidates[i], list, i);
				list.remove(list.size()-1);
			}
		}
		
	}

}

從給定無序陣列中選取任意個數(不可重複),使其和為給定值(leetcode40):

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
思路:回溯法的練習題,按照上題思路,可以先將陣列排序,不同點是因為不可以重複,遞迴呼叫要從當前位置的下一個數開始取。
class Solution {
  
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
    	helper(candidates,target,new ArrayList<Integer>(),0);
    	return res;
    }
    
    private void helper(int[] candidates, int target, ArrayList<Integer> list,int index) {
		
	if( target == 0){
            if(!res.contains(list)){
		res.add(new ArrayList<>(list));
            }
	}
	for (int i = index; i < candidates.length; i++) {
			if(candidates[i] <= target){
				list.add(candidates[i]);
				helper(candidates, target-candidates[i], list, i+1);
				list.remove(list.size()-1);
			}
		}
		
	}
}