Leetcode #39. Combination Sum 组合求和 解题报告

1 解题思想

原题是说给定一些数字和一个目标值,从这些数字中挑选几个加起来,加起来后他的和正好等于目标值,其中一个数字可以选择多次。要求输出的不能有重复,并且组内的顺序是不能降序的。

这道题首先必须要想到的就是排序了,排序是非常基本,又非常常用的一种操作。

然后我们需要排除重复的(注意可以重复选择一个数,所以重复的最好先去掉,因为我们需要进行递归回溯,这样做可以降低无谓的开销)

随后我们就开始求解,求解的做法是采用递归的回溯,每一次递归传递还需要的数值reserve,同时记录已经选择的数字,原则上当前选择的数字需要大于等于上一个,所以再加上一个index表示可以从哪个索引开始选择。

然后遇到reserve为0就加入最终结果,遇不到就不加咯~~~

2 原题

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]

3 AC解

public class Solution {
    /**
     * 可以用一个计数的数组来降低开销,递归的时候只改变数组里选择的值,最后reserve=0再生成list
     * **/
    int n;
    int nums[];
    List<List<Integer>> result;
    //当前集合,当前使用的数字位置,当前还剩多少
    public void find(List<Integer> values,int index,int reserve){
        if(reserve==0){
            ArrayList<Integer> item=new ArrayList<Integer>();
            item.addAll(values);
            result.add(item);
        }
        for(int i=index;i<n;i++){
            if(nums[i]<=reserve){
                values.add(nums[i]);
                find(values,i,reserve-nums[i]);
                values.remove(values.size()-1);
            }
        }
    }
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        //排序然后去除重复的
        Arrays.sort(candidates);
        //去除重复,这样省心
        int i,j,k,n;
        n=1;
        for(i=1;i<candidates.length;i++){
           if(candidates[i]!=candidates[i-1]){
               candidates[n++]=candidates[i];
           } 
        }
        this.nums=candidates;
        this.n=n;
        this.result=new ArrayList<List<Integer>>();
        find(new ArrayList<Integer>(),0,target);
        return this.result;


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值