常见算法 - 从给定数组中选取任意个数(可重复),使其和为给定值。

回溯法练习:


从给定有序数组中选取任意个数(可重复),使其和为给定值(leetcode39):

Example 1:

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

思路:回溯法的练习题。因为可以重复,注意递归调用时可以从当前位置开始取。

class Solution {
  
	List> res = new ArrayList>();
    public List> combinationSum(int[] candidates, int target) {
        
    	helper(candidates,target,new ArrayList(),0);
    	return res;
    }
    
	private void helper(int[] candidates, int target, ArrayList 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> res = new ArrayList>();
    public List> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
    	helper(candidates,target,new ArrayList(),0);
    	return res;
    }
    
    private void helper(int[] candidates, int target, ArrayList 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);
			}
		}
		
	}
}

你可能感兴趣的:(笔记,算法)