Combination Sum I && II

还是递归 但是边界条件以及边界上的处理不容易搞清楚(一开始我就把target==0的情况漏掉了,然后又把target==0放在了target<0||candidates.length<=0的后面,导致candidates.length==0&&target==0的情况不会被target==0处理,唉,考虑不清楚)

public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
if (target == 0){
results.add(new ArrayList<Integer>());
return results;
}
if (target < 0 || candidates.length <= 0)
return results;
int[] newCandidates = Arrays.copyOfRange(candidates, 0, candidates.length-1);
int max = candidates[candidates.length-1];
int num = target / max;
for (int i = 0; i <= num; ++i){
ArrayList<ArrayList<Integer>> newResults = combinationSum(newCandidates, target-i*max);
for (int j = 0; j < newResults.size(); ++j)
for (int k = 0; k < i; ++k)
newResults.get(j).add(max);
results.addAll(newResults);
}
return results;
}
}

汗 II就直接改了改代码通过了。。。

public class Solution {
public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
if (target == 0){
results.add(new ArrayList<Integer>());
return results;
}
if (target < 0 || candidates.length <= 0)
return results;
int[] newCandidates = Arrays.copyOfRange(candidates, 0, candidates.length-1);
int max = candidates[candidates.length-1];
for (int i = 0; i <= 1; ++i){
ArrayList<ArrayList<Integer>> newResults = combinationSum2(newCandidates, target-i*max);
for (int j = 0; j < newResults.size(); ++j)
for (int k = 0; k < i; ++k)
newResults.get(j).add(max);
for (int j = 0; j < newResults.size(); ++j)
if (!results.contains(newResults.get(j)))
results.add(newResults.get(j));
}
return results;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值