zoukankan      html  css  js  c++  java
  • [LeetCode] Add to List 39. Combination Sum Java

    题目:Given a set of candidate numbers (C) (without duplicates) 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.
    • 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,求出由数组元素组成的数组和等于target的所有可能(数组中的元素可以复用),数组所有元素都为正整数,不能包含相同的数组。这道题要求出所有可能,所以可以使用回溯的方法。我们用一个start变量存储子数组开始的位置,用int remian保留target减去当前求值数组的和,这样我们就可以转化为 在start和candidates.length-1中求 和等于target的数组。理解不够深入,讲得不是很清楚,具体可以看一下代码。。

    代码:

    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<Integer> array= new ArrayList<>();
            List<List<Integer>> list = new ArrayList<>();
            int start=0;
            int remain=target;
            backTracking(list,array,candidates,start,remain);
            return list;
        }
    	
    	public void backTracking(List<List<Integer>> list,List<Integer> array,int[] candidates,int start,int remain) {
    		if(remain<0)
    			return;
    		else if(0==remain){	//有解
    			list.add(new ArrayList<>(array));
    		}else{
    			for(int i=start;i<candidates.length;i++){
    				if(i>0&&candidates[i]==candidates[i-1]) continue;  //这一步操作主要是去重
    				array.add(candidates[i]);
    				backTracking(list, array, candidates, i, remain-candidates[i]);    //这里注意一下是i,因为元素可以重复利用
    				array.remove(array.size()-1);
    			}
    		}
    		return;
    	}
    }
    

      

  • 相关阅读:
    电商第一季函数笔记(1)
    沈逸老师PHP魔鬼特训笔记(2)
    PHP读书笔记(3)-常量
    2015/8/9 到家了,学完了CodeCademy的Python
    2015/8/4 告别飞思卡尔,抛下包袱上路
    2015/6/23 浪潮过去,我才来
    方维团购系统二次开发,项目经验
    方维团购系统整合云短信网短信平台,方维系统整合短信平台
    方维团购系统,下订单保存多个收货地址
    PHP木马查杀文件,木马查杀插件
  • 原文地址:https://www.cnblogs.com/271934Liao/p/6943925.html
Copyright © 2011-2022 走看看