class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
vector<int> records;
vector<bool> used(nums.size(), false);
tryGetSum(nums, res, records, used, target, 0);
return res;
}
private:
void tryGetSum(vector<int>& nums, vector<int>& res, vector<int>& records, vector<bool>& used, int target, int start) {
if (records.size() == 2 &&
(nums[records[0]] + nums[records[1]]) == target){
res.push_back(records[0]);
res.push_back(records[1]);
used[records[0]] = true;
used[records[1]] = true;
return;
} else if (records.size() == 2 && (nums[records[0]] + nums[records[1]]) != target){
return;
}
for (int i = start; i < nums.size(); i++) {
if (!used[i]) {
used[i] = true;
records.push_back(i);
tryGetSum(nums, res, records, used, target, i + 1);
records.pop_back();
used[i] = false;
}
}
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hash;
vector<int> v;
for(int i = 0; i < nums.size(); i++) {
int search = target - nums[i];
if (hash.find(search) != hash.end()) {
v.push_back(hash[search]);
v.push_back(i);
return v;
}
hash[nums[i]] = i;
}
return v;
}
};