【LeetCode】216.Combination Sum III(Medium)解题报告

来源:互联网 发布:java获取jquery ip 编辑:程序博客网 时间:2024/05/21 13:47

【LeetCode】216.Combination Sum III(Medium)解题报告

题目地址:https://leetcode.com/problems/combination-sum-iii/description/
题目描述:

  Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:Input: k = 3, n = 7Output:[[1,2,4]]Example 2:Input: k = 3, n = 9Output:[[1,2,6], [1,3,5], [2,3,4]]

  这道题要求数字是0到9,不可重复使用,要求数字的个数为k。比较巧的地方就是if(k==0)及后面的k-1。

Solution:

class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {        List<List<Integer>> res = new ArrayList<>();        List<Integer> tempList = new ArrayList<>();        combo(res,k,n,tempList,1);        return res;    }    public void combo(List<List<Integer>> res,int k,int n,List<Integer> tempList,int index){        if(k==0){            if(n==0){                res.add(new ArrayList<>(tempList));            }            return;        }        for(int i=index;i<=n/k&&i<10;i++){            tempList.add(i);            combo(res,k-1,n-i,tempList,i+1);            tempList.remove(tempList.size()-1);        }    }}

Date:2017年12月12日

原创粉丝点击