코딩테스트

[leetcode] 216. Combination Sum III

nayoon 2024. 6. 15. 00:34

 

문제

class Solution {
    static List<List<Integer>> result;
    static List<Integer> list;
    static int limit;
    static int sum;
    public List<List<Integer>> combinationSum3(int k, int n) {
        result = new ArrayList<>();
        list = new ArrayList<>();

        for(int i = 0; i < k; i++) {
            list.add(0);
        }

        limit = k;
        sum = n;

        combination(0, 0, 1);
        return result;
    }

    public void combination(int s, int n, int index) {
        if (n == limit) {
            if (s == sum) {
                result.add(new ArrayList<>(list));
            }
            return;
        }
        
        for(int i = index; i < 10; i++) {
            list.set(n, i);
            combination(s + i, n + 1, i + 1);
        }
    }
}