Leetcode_216 组合总和 III

题目描述

Leetcode_216 组合总和 III_第1张图片

题解

基本就和77是一样的组合问题

import java.util.*;
public class Leetcode_216 {

    public List> combinationSum3(int k, int n) {
        List templist = new ArrayList<>();
        List> ret = new ArrayList<>();
        findcombination(k,n,1,templist,ret);
        return ret;


    }

    private int sum(List t)
    {
        int summ = 0;
        for(int i = 0;iget(i);

        }
        return summ;
    }

    private void findcombination(int k, int n, int start, List templist, List> ret)
    {

        if(templist.size() == k)
        {
            if(sum(templist)==n)
            {
                ret.add(new ArrayList<>(templist));
            }
        }

        for(int i = start;i<10;i++)
        {
            templist.add(i);
            findcombination(k,n,i+1,templist,ret);
            templist.remove(templist.size()-1);
        }

    }


    public static void main(String[] args)
    {
        List> ret = new ArrayList<>();

        Leetcode_216 a = new Leetcode_216();
        ret = a.combinationSum3(2,18);
        System.out.println(ret.toString());

    }
}

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