50014. Selection
難度:4/5
Second Try: 2/5 Used Time: 8:00
13
行的n - now_idx < s
是必要的剪枝。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#include <stdio.h>
#include <stdlib.h>
#include "subset.h"
int cmp(const void* a, const void* b){
return (*(int*)a - *(int*)b);
}
int solve(int* arr, int now_idx, int n, int k, int s){
if(s == 0 && k == 0){
return 1;
}
else if(k < 0 || s < 0 || n == now_idx || n - now_idx < s){
return 0;
}
else{
int pick = solve(arr, now_idx + 1, n, k - arr[now_idx], s - 1);
if(pick) return pick;
int not_pick = solve(arr, now_idx + 1, n, k , s );
if(not_pick) return not_pick;
return 0;
}
}
int subset(int numbers[], int n, int K, int S){
qsort(numbers, n, sizeof(int), cmp);
int i;
for(i = 0; i < n; i++) if(numbers[i] > K) break;
return solve(numbers, 0, i, K, S);
}
Morris 的簡潔寫法
1 |
|