Leecode 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:

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

题目翻译: 给一个数组C和一个目标值T, 找出所有的满足条件的组合:使得组合里面的数字之和等于T,并且一些数字可以从C中午先选择。

注意:

  1. 所有给定的数字均为正整数.(这意味着我们加corner case invalid check的时候要加一条,如果给定T不是正整数,我们就没必要在往下进行了)

  2. 所有的答案组中要满足升序排列.

  3. 最后的答案数组不能包含重复答案.


注意一点,这里给出的数组里面数字不是重复的。

解决思路:采取递归的思想。我们先将数组从小到大排列一下,这样结果才符合题意。如何递归呢,我们先从第一个数字开始,用T减去这第一个数字,结果记为

T1,再从数组的第二数字开始,看剩下的这些数字加起来是否会等于T1,依次递归。

下面是代码,有几个细节要注意!



import java.util.*;
public class Solution {
    public ArrayList> combinationSum(int[] candidates, int target) {
        ArrayList> m=new ArrayList>();//不要创建全局变量,因为多次测试会保存上次结果,导致ac不了
        
        ArrayList M=new ArrayList();
        Arrays.sort(candidates);
        DFS(m,M,0,candidates,target);
        
        return m;
    }
    public void DFS(ArrayList> m,ArrayList M,int index,int []can,int sum){
        if(sum==0){
            m.add(new ArrayList(M));//注意要新建一个ArrayList
        	return ;
        }
        if(sum<0)
            return ;
        for(int i=index;i


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值