解题思路:
从第i个candidate开始,有k个选择(要保证remain=target-candidate[i]*k>=0) 分别递归下去,一开始我以为可以用备忘录方法存储已经算出的值,后来发现不行,为什么?因为每次算的即使同样的值,用到的candidate也不一样,因此不算是同样的子问题.比如5可以表示为2 2 1 也可以表示为 2 3 不能认为是同一个子问题.
解题代码:
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates=candidates;
return combine(candidates.length-1,target);
}
public List<List<Integer>> combine(int k,int target)
{
if(k==0)
{
if(target%candidates[0]==0)
{
List<List<Integer>>results=new ArrayList<List<Integer>>();
List<Integer> ele=new ArrayList<Integer>();
for(int i=0;i<target/candidates[0];i++)ele.add(candidates[0]);
results.add(ele);
return results;
}else
{
List<List<Integer>>results=new ArrayList<List<Integer>>();
return results;
}
}
if(target==0)
{
List<List<Integer>>results=new ArrayList<List<Integer>>();
results.add(new ArrayList<Integer>());
return results;
}
List<List<Integer>>results=new ArrayList<List<Integer>>();
for(int i=target/candidates[k];i>=0;i--)
{
int remain=target-candidates[k]*i;
List<List<Integer>> sub_list=combine(k-1,remain);
if(sub_list.isEmpty())continue;
for(List<Integer> sub:sub_list)
{
for(int j=0;j<i;j++)
sub.add(candidates[k]);
results.add(sub);
}
}
return results;
}
private int[] candidates;
}