All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0216_combination_sum_iii.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0201_0300.s0216_combination_sum_iii;

// #Medium #Array #Backtracking

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

@SuppressWarnings("java:S5413")
public class Solution {
    public List> combinationSum3(int k, int n) {
        List> res = new ArrayList<>();
        solve(k, n, new ArrayList<>(), res, 0, 1);
        return res;
    }

    private void solve(
            int k, int target, List temp, List> res, int sum, int start) {
        if (sum == target && temp.size() == k) {
            res.add(new ArrayList<>(temp));
            return;
        }
        if (temp.size() >= k) {
            return;
        }
        if (sum > target) {
            return;
        }
        for (int i = start; i <= 9; i++) {
            temp.add(i);
            solve(k, target, temp, res, sum + i, i + 1);
            temp.remove(temp.size() - 1);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy