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] 

z这道题是根据给定的数组和target,算出数组中数字之和满足target的元素,元素可以重复出现。

用的是回朔法。

回朔法就是要用stack来模拟。

具体思路如下:

1. 对给定数组 candidtas[]进行排序。

2. 对candidates[]元素从大到小遍历,得到candidtates[i]

3.

if(candidates[i]+sum==target){
				
				stack.push(i);
				//Stack tobeadd=(Stack<Integer>) stack1.clone ();
				listtmp.add((Stack<Integer>) stack.clone ());
				stack.pop();
				i--;
				
			}
else if(candidates[i]+sum>target){
				i--;
			}
else if(candidates[i]+sum<target){
				sum+=candidates[i];
				stack.push(i);
			}
就是如果和满足target,那么加入结果集,并且弹出stack顶的元素,并且i--,寻找下一个由更小元素组成的可能。

如果和大于target,那么就弹出stack顶元素,并且i--,寻找下一个由更小元素组成的可能。

如果和小于target,那么就继续把当前元素压栈。重复以上循环。


这里面有一个判断条件,就是如果--i<0。并且!stack.isEmpty();说明在当前stack情况下试了更小元素的所有可能,都不满足,那么,就需要把satck中元素继续弹出来,加入更小的元素进去。


上代码

import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public class Combination_Sum {
	public static List<List<Integer>> combinationSum(int[] candidates, int target) {
		
		Stack<Integer> stack=new Stack<>();
		List<Stack<Integer>> listtmp=new ArrayList<>();
		//List<List<Map<Integer, Integer>>> resultList=new ArrayList<>();
		int sum=0;
		for(int i=candidates.length-1;i>=0||!stack.isEmpty();){
			if(i<0){
				if(stack.isEmpty())break;
				i=stack.pop();
				sum-=candidates[i];
				i--;
				continue;
			}
			if(candidates[i]+sum==target){
				
				stack.push(i);
				//Stack tobeadd=(Stack<Integer>) stack1.clone ();
				listtmp.add((Stack<Integer>) stack.clone ());
				stack.pop();
				i--;
				
			}
			else
			if(candidates[i]+sum>target){
				i--;
			}
			else
			if(candidates[i]+sum<target){
				sum+=candidates[i];
				stack.push(i);
			}
			
			
		}
		List<List<Integer>> result=new ArrayList<>();
		for (Stack<Integer> keyarray : listtmp) {
			List<Integer> childIntegers=new ArrayList<>();
			for(Integer key:keyarray){
				childIntegers.add(0,candidates[key]);
			}
			result.add(childIntegers);
		}
		return result;
        
    }
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] candidates={1,2};
		int target=4;
		combinationSum(candidates, target);
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值