LeetCode OJ算法题(三十八):Combination Sum

题目:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

解法:

这道题与之前的2Sum,3Sum,4Sum很相似,但这里加数的个数并没有给定,而且C中元素还可以不限次数的使用,在这么庞大的解空间里寻找所有答案,考虑使用分治算法。

首先对C进行排序,这样可以使得待会回溯时,较小的元素始终在前面。

接下来的问题问题可以分为两个子问题,以{2,3,6,7},7为例:包含第一个元素的所有解{2,3,6,7},5,和不包含第一个元素的所有解{3,6,7},7,开始递归,递归结束的条件是:

1、若target=0,则问题找到一组解,把当前的路径保存加入list集合中;

2、若target<0,则问题求解失败,回溯到上一状态,尝试下一种可能;

3、若集合C中已经没有第一个元素,则回溯到上一状态,尝试下一种可能。

注意这里没有用ArraList保存路径是因为在求解过程中要不停的更改ArrayList的值,这样会难以控制,所以偷懒用String来保存路径了- -!

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class No38_CombinationSum {
	public static void main(String[] args){
		System.out.println(combinationSum(new int[]{1}, 1));
	}
	public static List<List<Integer>> combinationSum(int[] candidates, int target) {
		Arrays.sort(candidates);
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        String s = "";
        fun(candidates, target, 0, list, s);
        return list;
    }
	public static void fun(int[] candidates, int target, int i, List<List<Integer>> list, String s){
		if(target<0){
			return;
		}
		if(target == 0){
			List<Integer> element = new ArrayList<Integer>();
			String[] sa = s.split(",");
			for(int k=1;k<sa.length;k++){
				element.add(Integer.valueOf(sa[k]));
			}
			list.add(element);
			return;
		}
		if(i >= candidates.length)
			return;
		fun(candidates, target, i+1, list, s);
		fun(candidates, target-candidates[i], i, list, s+","+candidates[i]);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值