我的leetcode代码已经放入 github:https://github.com/gaohongbin/leetcode
题目:给定一个整型数组candidates,和一个目标值target,使用数组中的数组成target,找出所有的组合。例如: candidates = {2,3,6,7}; target =7 ; 则返回的结果为:[[7],[2,2,3]] 。 题目说明,candidates中的数字全为正数,target也全为正数。 并且返回的结果中candidates中的数可以是重复的,而且不限次数的重复。但每一种组合只能出现一次。
思路:这个题目和我博客中的另一篇文章比较像:http://blog.csdn.net/mmchinamm/article/details/52104302 只是那个文章中每一种组合中的元素都不能重复,本题目可以重复,而且判断条件也有差别。但是我们可以稍加变化。本题中,我们将low和high分别初始化为0和candidates.length-1,我们可以首先一直往列表中添加第一个元素,low和high不变,加到一定程度不满足要求时,回退一个第一个元素,这时low++,high不变,进行递归。
代码:
/**
* 题目:给定一个整型数组candidates,和一个目标值target,使用数组中的数组成target,找出所有的组合。
* 例如: candidates = {2,3,6,7}; target =7 ; 则返回的结果为:[[7],[2,2,3]] 。
* 题目说明,candidates中的数字全为正数,target也全为正数。 并且返回的结果中candidates中的数可以是重复的,而且不限次数的重复。但每一种组合只能出现一次。
*
* 思路:这个题目和我博客中的另一篇文章比较像:http://blog.csdn.net/mmchinamm/article/details/52104302 只是那个文章中每一种组合中的元素都不能重复,本题目可以重复,而且判断条件也有差别。但是我们可以稍加变化。
* 本题中,我们将low和high分别初始化为0和candidates.length-1,我们可以首先一直往列表中添加第一个元素,low和high不变,加到一定程度不满足要求时,回退一个第一个元素,这时low++,high不变,进行递归。
*/
import java.util.ArrayList;
import java.util.List;
public class Leetcode39 {
public static void main(String[] args){
int[] nums = {2,3,6,7};
int target = 7;
List<List<Integer>> list = combinationSum(nums,target);
System.out.println(list);
}
/**
* 题目中给出的函数样式,最核心的代码是下一个函数combinationSum_1.
* @param candidates
* @param target
* @return
*/
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> subList = new ArrayList<Integer>();
if(candidates == null)
return list;
combinationSum(candidates, target, 0, candidates.length-1, list, subList);
return list;
}
/**
*
* @param nums: candidates数组
* @param target
* @param low: low和high表示在nums的该区间内进行组合。
* @param high
* @param list: 最终题目要返回的结果,这里传的是一个引用
* @param subList: list列表的子列表。
*/
public static void combinationSum(int[] nums, int target, int low, int high, List<List<Integer>> list,List<Integer> subList){
if(nums == null)
return ;
if(target == 0){
if(subList.size() == 0)
return ;
List<Integer> subList_1 = new ArrayList<Integer>();
for(int i=0;i<subList.size();i++)
subList_1.add(subList.get(i));
list.add(subList_1);
return ;
}
if(low > high)
return ;
if(target<0)
return ;
subList.add(nums[low]);
combinationSum(nums, target-nums[low], low, high, list, subList); //先使劲加第一个元素,加了以后low不变
subList.remove(subList.size()-1);
combinationSum(nums, target, low+1, high, list, subList); //回退一个元素,low++
}
}