天天看點

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);
        }
    }
}