39. Combination Sum

给你一个候选数字的集合(不含重复的数字)和一个目标数,找出候选集中所有唯一的组合数,其中组合数的

和为目标数。

同样的数字可以使用多次。

1. 回溯法

public List<List<Integer>> combinationSum(int[] candidates, int target)
	{
		// 存储符合条件的结果(二维列表)
		List<List<Integer>> list = new ArrayList<>();
		Arrays.sort(candidates);
		backtrack(list, new ArrayList<>(), candidates, target, 0);
		return list;
	}
	
	private void backtrack(List<List<Integer>> list, List<Integer> tempList, 
			int [] nums, int remain, int start)
	{
		if (remain < 0)
			return;
		else if (remain == 0)
			// 构造一个包含指定集合元素的列表
			list.add(new ArrayList<>(tempList));
		else
		{
			for (int i=start; i<nums.length; i++)
			{
				tempList.add(nums[i]);
				// not i + 1 because we can reuse same elements
				backtrack(list, tempList, nums, remain-nums[i], i);
				tempList.remove(tempList.size()-1);
			}
		}
	}
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值