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

回溯法练习:


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

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值