算法系列——Combination Sum

来源:互联网 发布:轰炸手机号码软件下载 编辑:程序博客网 时间:2024/06/06 02:18

题目描述

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]
]

解题思路

像这种结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,相类似的题目有 Path Sum II 二叉树路径之和之二,Subsets II 子集合之二,Permutations 全排列,Permutations II 全排列之二,Combinations 组合项等等,如果仔细研究这些题目发现都是一个套路,都是需要另写一个递归函数,每次调用新的递归函数时,此时的target要减去当前数组的的数,具体看代码如下:

程序实现

public class Solution {    private List<List<Integer>> result=new ArrayList<List<Integer>>();    public List<List<Integer>> combinationSum(int[] candidates, int target) {        if(candidates==null||candidates.length==0||target<0)            return result;        Stack<Integer> c=new Stack<Integer>();        backTracking(candidates,target,0,c);        return result;    }    private void  backTracking(int[] candidates,int target,int start,Stack<Integer> c){        if(target<0)            return;        if(target==0){            result.add(new ArrayList<Integer>(c));            return;        }        for(int i=start;i<candidates.length;i++){            target-=candidates[i];            c.push(candidates[i]);            backTracking(candidates,target,i,c);            c.pop();            target+=candidates[i];        }    }}
原创粉丝点击