Leetcode39&&Leetcode40 组合总和

题目描述

Leetcode39&&Leetcode40 组合总和_第1张图片

题解

很经典的题目

import java.util.*;

public class Leetcode_39 {

    public List> combinationSum(int[] candidates, int target) {

        List templist = new ArrayList<>();
        List> ret = new ArrayList<>();

        findcs(candidates,target,templist,ret,0);


        return ret;



    }


    private void findcs(int[] candidates, int target, List templist, List> ret, int start)
    {
        if(target<0) return;
        else if(target==0) ret.add(new ArrayList<>(templist));

        else {

            for (int i = start; i < candidates.length; i++) {
                templist.add(candidates[i]);
                findcs(candidates, target-candidates[i], templist, ret, i);
                templist.remove(templist.size() - 1);


            }
        }
    }

    public static void main(String[] args)
    {
        Leetcode_39 test = new Leetcode_39();
        int[] c = {2,3,6,7};
        int target = 7;
        List> ret = new ArrayList<>();
        ret = test.combinationSum(c,target);
        System.out.println(ret.toString());
    }
}

参考博客

题目描述

Leetcode39&&Leetcode40 组合总和_第2张图片

主要是个重复元素的删除问题

import java.util.*;

public class Leetcode_40 {

    public List> combinationSum2(int[] candidates, int target) {

        List templist = new ArrayList<>();
        List> ret = new ArrayList<>();
        Arrays.sort(candidates);

        findcs(candidates,target,templist,ret,0);


        return ret;

    }



    private void findcs(int[] nums, int remain, List templist, List>ret, int start)
    {

        if(remain<0) return;

        else if(remain==0) ret.add(new ArrayList<>(templist));
        else
        {
            for(int i = start; iif(i > start && nums[i] == nums[i-1]) continue; //跳过重复元素
                templist.add(nums[i]);
                findcs(nums,remain-nums[i],templist,ret,i+1);
                templist.remove(templist.size()-1);
            }
        }




    }

    public static void main(String[] args)
    {
        Leetcode_40 test = new Leetcode_40();
        int[] c = {10,1,2,7,6,1,5};
        int target = 8;
        List> ret = new ArrayList<>();
        ret = test.combinationSum2(c,target);
        System.out.println(ret.toString());
    }
}

你可能感兴趣的:(编码,Leetcode)