leetCode-Combination Sum III

来源:互联网 发布:apache base64 maven 编辑:程序博客网 时间:2024/06/05 19:56

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]]

Solution:

//想象成一个三层的树,用深度遍历的方式遍历,如果遇到合适的路径,那么添加到list中,要注意的地方是需要回退路径的时候需要清除之前的路径class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {        int[] nums = new int[]{1,2,3,4,5,6,7,8,9};        List<List<Integer>> list = new ArrayList<List<Integer>>();        helper(list,new ArrayList<Integer>(),nums,k,n,0);        return list;    }    public void helper(List<List<Integer>> list,List<Integer>line,int[] nums,int k,int n,int start){    if(n == 0 && k ==0){        list.add(new ArrayList(line));    }else{        for(int i = start;i < nums.length && k > 0 && n > 0;i++){            line.add(nums[i]);            helper(list,line,nums,k - 1,n - nums[i],i + 1);            line.remove(line.size() - 1);        }    }}}