Leetcode - Combination Sum III

Leetcode - Combination Sum III_第1张图片

My code:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List> combinationSum3(int k, int n) {
        ArrayList> result = new ArrayList>();
        if (k <= 0 || k > 9 || n <= 0)
            return result;
        ArrayList combination = new ArrayList();
        getCombinations(1, 1, k, 0, n, combination, result);
        return result;
    }
    
    private void getCombinations(int begin, int count, int k, int sum, int n,
                                ArrayList combination, ArrayList> result) {
        if (count > k)
            return;
        else {
            for (int i = begin; i <= 9; i++) {
                int temp = sum + i;
                if (temp > n)
                    break;
                else if (temp == n) {
                    if (count < k)
                        break;
                    else {
                        combination.add(i);
                        result.add(new ArrayList(combination));
                        combination.remove(combination.size() - 1);
                        break;
                    }
                }
                else {
                    combination.add(i);
                    getCombinations(i + 1, count + 1, k, temp, n, combination, result);
                    combination.remove(combination.size() - 1);
                }
            
            }
        }
        
    }
}

My test result:

Leetcode - Combination Sum III_第2张图片
Paste_Image.png

还是差不多的思路。然后需要限定长度是k,所以加了一个统计个数的count

**
总结: Array, DFS
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public List> combinationSum3(int k, int n) {
        ArrayList> ret = new ArrayList>();
        if (k < 1 || n < 1)
            return ret;
        ArrayList group = new ArrayList();
        helper(1, 0, 0, k, n, ret, group);
        return ret;
    }
    
    private void helper(int begin, int sum, int numbers, int k, int n,
                            ArrayList> ret, ArrayList group) {
        if (numbers >= k) { // if numbers == k, then detect whether sum == n
            if (sum != n) {
                return;
            }
            else {
                ret.add(new ArrayList(group));
                return;
            }
        }
        else if (sum >= n) // if numbers < k and sum >= n, then return without consideration of sum
            return;
        else { // if numbers < k and sum < n, then explore it with dfs
            for (int i = begin; i < 10; i++) {
                group.add(i);
                helper(i + 1, sum + i, numbers + 1, k, n, ret, group);
                group.remove(group.size() - 1);
            }
        }
    }
}

感觉我这次写的逻辑更加清晰。没什么难度。

Anyway, Good luck, Richardo!

你可能感兴趣的:(Leetcode - Combination Sum III)