Leetcode - Combination Sum III

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.

Ensure that numbers within the set are sorted in ascending order.

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

 [balabala] 这题本身思路是常规的递归回溯,奇怪的是实现1可以被Accept,实现2会编译不通过,但是在Eclipse中是可以编译通过的,只是有个warning。回头有时间查查这部分JAVA语法。

 

    // Implementation 1: Accept
    public List<List<Integer>> combinationSum3(int k, int n) {
        ArrayList<Integer> item = new ArrayList<Integer>();
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        recur(1, k, n, result, item);
        return result;
    }
    
    private void recur(int start, int k, int n, List<List<Integer>> result, ArrayList<Integer> item) {
        if (k == 0) {
            if (n == 0)
                result.add((List<Integer>) item.clone());
            return;
        }
        for (int i = start; i <= 9; i++) {
            item.add(i);
            recur(i + 1, k - 1, n - i, result, item);
            item.remove(item.size() - 1);
        }
    }

    // Implementation 2: Compiler Error
    public ArrayList<ArrayList<Integer>> combinationSum3(int k, int n) {
        ArrayList<Integer> item = new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        recur(1, k, n, result, item);
        return result;
    }
    
    private void recur(int start, int k, int n, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> item) {
        if (k == 0) {
            if (n == 0)
                result.add((ArrayList<Integer>) item.clone());
            return;
        }
        for (int i = start; i <= 9; i++) {
            item.add(i);
            recur(i + 1, k - 1, n - i, result, item);
            item.remove(item.size() - 1);
        }
    }

 

你可能感兴趣的:(LeetCode)