-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclosest_3sum.cpp
More file actions
85 lines (65 loc) · 1.93 KB
/
closest_3sum.cpp
File metadata and controls
85 lines (65 loc) · 1.93 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//
// Created by Mayank Parasar on 2020-05-17.
//
/*
* Given a list of numbers and a target number n, find 3 numbers in the list that sums closest to the target number n.
* There may be multiple ways of creating the sum closest to the target number, you can return any combination
* in any order.
Here's an example and some starter code.
def closest_3sum(nums, target):
# Fill this in.
print(closest_3sum([2, 1, -5, 4], -1))
# Closest sum is -5+1+2 = -2 OR -5+1+4 = 0
# print [-5, 1, 2]
*/
#include <iostream>
#include <vector>
using namespace std;
vector<int> nums = {2, 1, -5, 4};
void print_combinations_new(vector<vector<int> >& ans,
vector<int>& tmp, int n, int left, int k) {
if(k == 0) {
ans.push_back(tmp);
return;
}
// i iterates from left to n-1. First time
// left will be 0
for(int i = left; i < n; ++i) {
tmp.push_back(nums[i]);
print_combinations_new(ans, tmp, n,i+1, k-1);
// popping out last inserted element from the vector
tmp.pop_back();
}
}
int main() {
vector<vector<int>> result;
vector<int> tmp;
int size = 3;
int start = 0;
print_combinations_new(result, tmp, nums.size(), start, size);
// this is the final dara structure:
vector<pair<vector<int>, int>> vector_sum;
for(auto i : result) {
int sum = 0;
for(auto k : i) {
sum += k;
// cout << k << " ";
}
vector_sum.push_back(make_pair(i, sum));
// cout << endl;
}
int closest_sum = -1; // set this to find the closest sum
uint32_t min = -1;
vector<int> min_vector;
for(auto i : vector_sum) {
if(abs(i.second-closest_sum) < min) {
min = abs(i.second-closest_sum);
min_vector = i.first;
}
}
cout << "Minimum vector is:" << endl;
for(auto i : min_vector)
cout << i << " ";
cout << endl;
return 0;
}