`
testforvln
  • 浏览: 18905 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论
  • superich2008: 1、去重可以用Set集合2、在排序后,相邻2个元素如果相同可以 ...
    4Sum

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;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics