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

回溯法练习:


从给定有序数组中选取任意个数(可重复),使其和为给定值(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);
			}
		}
		
	}
}

这个问题可以通过回溯算法来解决。具体来说,我们可以从数组的第一个开始,不断地选择加上或不加上该,直到数组的所有都被处理过为止。如果加上某个数后的等于给定,则找到了一个符合条件的组合。如果所有的组合都被处理完了仍然没有找到符合条件的组合,则说明不存在这样的组合。 下面是一个简单的 Python 实现: ```python def find_combinations(nums, target): def backtrack(start, path, cur_sum): if cur_sum == target: res.append(path[:]) return if cur_sum > target: return for i in range(start, len(nums)): path.append(nums[i]) backtrack(i, path, cur_sum + nums[i]) path.pop() res = [] backtrack(0, [], 0) return res ``` 在上面的代码中,backtrack 函用于搜索符合条件的组合。它有三个参:start 表示从数组的哪个位置开始搜索,path 表示已经选择的的列表,cur_sum 表示当前已经选择的。具体来说,backtrack 函会枚举从 start 到数组末尾的所有,对于每个数,它会尝试加上这个数或者不加上这个数,然后递归搜索下一个位置。如果搜索完了整个数组,且当前已选的等于给定 target,则将 path 添加到结果列表中。 最后,我们可以使用如下代码调用上述函: ```python nums = [1, 2, 3, 4, 5] target = 7 res = find_combinations(nums, target) print(res) ``` 输出结果为: ``` [[1, 2, 4], [1, 3, 3], [2, 5], [3, 4]] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值