天天看点

Combination Sum III 找出Sum符合要求的组合系列3

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

Output:

[[1,2,4]]
      

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]
      

----------------------------------------------------------------------------------------------------------------------------------------

题目看上去长了很多。但万变不离其宗。

跟之前的系列1,和系列2的区别:

1. 以前是任意的array,现在我们的array是一个1 ... 9的固定array

2. 约束组合中元素的个数为k 

array中的元素是只能使用一次的。

运行时间:

Combination Sum III 找出Sum符合要求的组合系列3

代码:

public class CombinationSumIII {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new LinkedList<>();
        doCombinationSum3(result, new LinkedList<>(), 1, k, n);
        return result;
    }

    private void doCombinationSum3(List<List<Integer>> result, List<Integer> curList, int val, int k, int n) {
        if (k == 0 && n == 0) {
            result.add(new ArrayList<>(curList));
            return;
        }
        if (n <= 0 || k <= 0) {
            return;
        }
        for (int i = val; i <= 9; i++) {
            curList.add(i);
            doCombinationSum3(result, curList, i + 1, k - 1, n - i);
            curList.remove(curList.size() - 1);
        }
    }
}