Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Recursion & Backtracking

Combination Sum with Digits 1 to 9

Medium · Recursion & Backtracking · Asked at Amazon, Microsoft, Google

Find every set of exactly k different numbers from 1 to 9 that add up to n. Print each set in increasing order, all sets in lexicographic order, one per line — or NONE if there is no such set.

Input

A single line with k and n.

Output

The sets, one per line, or NONE.

Constraints

Backtrack over the digits in increasing order, keeping the remaining sum; stop a branch when the remaining sum goes negative or k numbers are already chosen.

Example 1

Input

3 7

Output

1 2 4

Example 2

Input

3 9

Output

1 2 6
1 3 5
2 3 4

Example 3

Input

4 1

Output

NONE

Hints

  1. Choose the digits in increasing order so each set is built once.
  2. Track how much of the sum is still needed.
  3. Stop a branch as soon as the remaining sum is negative or k digits are used.

Approach

go(start, remaining): if k digits are chosen, record the set when remaining is 0. Otherwise try d = start … 9 with d ≤ remaining, choose it, recurse with (d + 1, remaining − d) and undo. Increasing order gives the required lexicographic output. Print NONE if nothing was recorded.

Complexity: O(C(9, k)) time · O(k) depth

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int k;
vector<int> cur;
vector<string> out;

void go(int start, int rem) {
    if ((int) cur.size() == k) {
        if (rem == 0) {
            string s;
            for (int i = 0; i < k; i++) s += to_string(cur[i]) + (i + 1 < k ? " " : "");
            out.push_back(s);
        }
        return;
    }
    for (int d = start; d <= 9 && d <= rem; d++) {
        cur.push_back(d);
        go(d + 1, rem - d);
        cur.pop_back();
    }
}

int main() {
    int n;
    cin >> k >> n;
    go(1, n);
    if (out.empty()) cout << "NONE\n";
    for (auto &s : out) cout << s << "\n";
    return 0;
}

Python solution

k, n = map(int, input().split())
cur, out = [], []


def go(start, rem):
    if len(cur) == k:
        if rem == 0:
            out.append(" ".join(map(str, cur)))
        return
    for d in range(start, min(9, rem) + 1):
        cur.append(d)
        go(d + 1, rem - d)
        cur.pop()


go(1, n)
print("\n".join(out) if out else "NONE")

Java solution

import java.util.*;

public class Main {
    static int k;
    static int[] cur;
    static StringBuilder out = new StringBuilder();

    static void go(int start, int rem, int depth) {
        if (depth == k) {
            if (rem == 0)
                for (int i = 0; i < k; i++) out.append(cur[i]).append(i + 1 < k ? " " : "\n");
            return;
        }
        for (int d = start; d <= 9 && d <= rem; d++) {
            cur[depth] = d;
            go(d + 1, rem - d, depth + 1);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        k = sc.nextInt();
        int n = sc.nextInt();
        cur = new int[k];
        go(1, n, 0);
        System.out.print(out.length() == 0 ? "NONE\n" : out);
    }
}

Solve Combination Sum with Digits 1 to 9 online · All practice problems