Combination Sum III

来源:互联网 发布:ubuntu启动脚本编写 编辑:程序博客网 时间:2024/06/06 12:36

Find all possible combinations of k numbers that add up to a numbern, 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 = 7

Output:

[[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]
思路:backtracking.跟之前的II差不多。

public class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {        List<List<Integer>> lists = new ArrayList<List<Integer>>();        if(k < 0 || n < 0) return lists;        ArrayList<Integer> list = new ArrayList<Integer>();        collect(lists, list, k, n, 0, 0, 1);        return lists;    }        public void collect(List<List<Integer>> lists, List<Integer> list, int k, int n, int count, int sum, int index) {        if(sum > n) return;        if(count == k && sum == n){            lists.add(new ArrayList<Integer>(list));            return;        }        for(int i=index; i<=9; i++){            sum += i;            count++;            list.add(i);            collect(lists, list, k, n, count, sum, i+1);            list.remove(list.size()-1);            count--;            sum -=i;        }    }}


0 0
原创粉丝点击