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 (a1, a2, … , 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] 

思路

先对数组进行升序排列,然后在用回溯法BS,这里用的递归调用实现的

 1 public class Solution {
 2     public List<List<Integer>> combinationSum(int[] candidates, int target) {
 3         Arrays.sort(candidates);
 4         List<List<Integer>> result = new ArrayList<List<Integer>>();
 5         getResult(result, new ArrayList<Integer>(), candidates, target, 0);
 6         
 7         return result;
 8     }
 9     
10     private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
11         if(target > 0){
12             for(int i = start; i < candidates.length && target >= candidates[i]; i++){
13                 cur.add(candidates[i]);
14                 getResult(result, cur, candidates, target - candidates[i], i);
15                 cur.remove(cur.size() - 1);
16             }//for
17         }//if
18         else if(target == 0 ){
19             result.add(new ArrayList<Integer>(cur));
20         }//else if
21     }
22 }

 

转载于:https://www.cnblogs.com/luckygxf/p/4239854.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值