leetCode 39.Combination Sum(组合总和) 解题思路和方法

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] 


思路:题意比较容易理解,首先想到的还是递归方法,思想是首先把=target的数保存到list,将<target的重新排列到数组,然后循环新的数组,寻找newArray,target-newarray[i]的最优解,最后将newlist添加上newArray[i]的值即可。

说的肯定不清楚,看代码,注释很详细:

public class Solution {
    public List<List<Integer>> combinationSum(int[] a, int t) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();
        Arrays.sort(a);//数组排序
        //各种特殊情况
        if(a.length == 0 || a[0] > t)
            return list;

        int len = 0;
        boolean isAdd = false;//控制与t相等的数只添加一次
        for(int i = 0; i< a.length;i++){
            if(a[i] == t){
                if(!isAdd){//如果未添加
                    List<Integer> al = new ArrayList<Integer>();
                    al.add(t);
                    list.add(al);
                    isAdd = true;//标记已添加
                }
            }else if(a[i] < t){//只要比target小的值,大的值肯定不满足,排除
                a[len++] = a[i];//新数组
            }
        }
        //只存在a[0] < target 或 a[0] > target
        if(a[0] > t)//肯定已没有符合要求的组合
            return list;
        //a[0] < target
        
        for(int i = 0; i < len; i++){//循环搜索符合要求的数字组合
        	int[] b = Arrays.copyOfRange(a, i, len);//不含>=t数据的新数组
        	if(a[i] > t)//如果a[i],肯定以后的数据已不符合,返回
        		break;
            //相等于已经有了一个值a[0]了    
            List<List<Integer>> newList = new ArrayList<List<Integer>>();
            newList = combinationSum(b,t-a[i]);
            if(newList.size() > 0){//里面有符合要求的数据
                for(int j = 0; j < newList.size();j++){
                    newList.get(j).add(a[i]);//新返回的各个值添加a[0]
                    Collections.sort(newList.get(j));//排序
                    list.add(newList.get(j));//最终添加
                }
            }
        }
        return list;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值