leetcode39. Combination Sum

题目描述:

简单点来说就是给你一个不包含重复元素的数组candidates和一个目标值 target,让你在candidates数组中找出所有相加能组合成目标值target的组合,但不允许结果重复如[2,3,3]和[3,3,2]应该算是一个结果。

解法分析:

我的思路是首先数组candidates一定要带顺序,然后从大到小来寻找组合。循环遍历当数组中的值x比目标值小的时候,可以进行基于x的组合子查找,查找方法就是改变目标值为target-x和一个最大值限制x,这样基于x的组合查找就不会去组合比x更大的值,防止了重复组合问题的发生。如果基于x的子查找有返回结果,那么在每个返回结果组合中加入x即是本次遍历中的一个结果,没有则返回空数组。代码如下:

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
	return combinationSum(candidates, target, candidates[candidates.length - 1]);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target, int max) {
	List<List<Integer>> result = new ArrayList<List<Integer>>();
	for (int i = 0; i < candidates.length; i++) {
	    if (candidates[i] > max) {
		break;
	    } else if (candidates[i] == target) {
		List<Integer> tmp = new ArrayList<Integer>();
		tmp.add(candidates[i]);
		result.add(tmp);
	    } else if (candidates[i] < target) {
		List<List<Integer>> tmpResult = combinationSum(candidates, target - candidates[i], candidates[i]);
		for (List<Integer> list : tmpResult) {
			list.add(candidates[i]);
			result.add(list);
		}
	    }
        }
	return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值