1068. Find More Coins

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805402305150976

1068 Find More Coins(30 分)

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she must pay the exact amount. Since she has as many as 10^4 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find some coins to pay for it.

Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (≤10^4 , the total number of coins) and M (≤10^2 , the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print in one line the face values V1 ≤ V​2 ≤ ⋯ ≤ V_k such that V_1 + V_2 + ⋯ + V_k = M. All the numbers must be separated by a space, and there must be no extra space at the end of the line. If such a solution is not unique, output the smallest sequence. If there is no solution, output “No Solution” instead.

Note: sequence {A[1], A[2], …} is said to be “smaller” than sequence {B[1], B[2], …} if there exists k≥1 such that A[i]=B[i] for all i<k, and A[k] < B[k].

Sample Input 1:

1
2
8 9
5 9 8 7 2 3 4 1

Sample Output 1:

1
1 3 5

Sample Input 2:

1
2
4 8
7 2 4 3

Sample Output 2:

1
No Solution

想法

先排序 肯定的

backtracking?感觉是

写了一个递归的版本,超时了一个点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Created by Zhao Xiaodong on 2018/8/23.
//
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N, M;
vector<int> s;
vector<int> a;
int sum = 0;
bool f(int k) {
if (sum == M)
return true;
for (int i = k; i < N; i++) {
s.push_back(a[i]);
sum += a[i];
if (sum == M)
return true;
else if (sum > M) {
sum -= a[i];
s.pop_back();
return false;
}
bool res = f(i + 1);
if (res) {
return true;
}
sum -= a[i];
s.pop_back();
}
return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> N >> M;
a = vector<int>(N);
for (int i = 0; i < N; i++) {
cin >> a[i];
}
sort(a.begin(), a.end());
bool res = f(0);
if (res) {
if (!s.empty()) {
cout << s[0];
for (int i = 1; i < s.size(); i++) {
cout << " " << s[i];
}
cout << "\n";
}
} else {
cout << "No Solution";
}
return 0;
}

有没有可以优化的地方?

TODO..

或许应该用DP吧