刷题05

组合

class Solution {
    List<List<Integer>> sum=new LinkedList<>();
    LinkedList<Integer> path=new LinkedList<>();
    public List<List<Integer>> combine(int n, int k) {
        get(n,k,1);
        return sum;
    }
    public void get(int n,int k,int startIndex)
    {
        if(path.size()==k)
        {
            sum.add(new LinkedList<>(path));
            return;
        }
        for(int i=startIndex;i<=n;i++)
        {
            path.add(i);
            get(n,k,i+1);
            path.removeLast();
        }
    }
}

组合总合Ⅲ

class Solution {
    List<List<Integer>> sum=new LinkedList<>();
    LinkedList<Integer> path=new LinkedList<>();
	public List<List<Integer>> combinationSum3(int k, int n) {
		get(n,k,1);
        return sum;
	}
    public void get(int n,int k,int startIndex)
    {
        if(path.size()==k&&n==0)
        {
            sum.add(new LinkedList<>(path));
            return;
        }
        for(int i=startIndex;i<=9;i++)
        {
            path.add(i);
            get(n-i,k,i+1);
            path.removeLast();
        }
    }
}
上一篇:二分答案例题


下一篇:构造