leetcode-题7--sum
非暴力不合作;深度优先
#include <iostream> #include <algorithm> #include <unordered_map> using namespace std; void dfs(const vector<int>&a,int ind1,int ind2,int tar,vector<int>&path) { if (a[ind1 - 1] + a[ind2 - 1] == tar) { path.push_back(ind1); path.push_back(ind2); return; } if (ind1 == ind2)return; dfs(a, ind1 + 1, ind2, tar, path); dfs(a, ind1, ind2 - 1, tar, path); } int main() { int a[4] = { 2,3,11,15 }; vector<int>nums(a, a + 4); vector<int>path; dfs(nums, 1, 4, 13, path); for (auto i : path) cout << i << endl; system("pause"); return 0; }
解法2:
网上炒的跪服:
#include <iostream> #include <algorithm> #include <unordered_map> using namespace std; int main() { int a[4] = { 2,3,11,15 }; unordered_map<int, int>nums; for (int i = 0; i < 4; ++i) nums[a[i]] = i; int tar; cin >> tar; for (int i = 0; i < 4; ++i) { int tem = tar - a[i]; if (nums.find(tem) != nums.end()) { int k = nums[tem]; if (k != i) cout << i+1 << ' ' << k+1 << endl; break; } } system("pause"); return 0; }