Approach
Depth-first search
For Partition Array Into Two Arrays to Minimize Sum Difference, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 53 lines of C++ from the credited upstream file 2035.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minimumDifference(vector<int>& nums) {4 const int n = nums.size() / 2;5 const int sum = accumulate(nums.begin(), nums.end(), 0);6 const int goal = sum / 2;7 const vector<int> lNums(nums.begin(), nums.begin() + n);8 const vector<int> rNums(nums.begin() + n, nums.end());9 int ans = INT_MAX;10 vector<vector<int>> lSums(n + 1);11 vector<vector<int>> rSums(n + 1);12 13 dfs(lNums, 0, 0, 0, lSums);14 dfs(rNums, 0, 0, 0, rSums);15 16 for (int lCount = 0; lCount <= n; ++lCount) {17 auto& l = lSums[lCount];18 auto& r = rSums[n - lCount];19 ranges::sort(r);20 for (const int lSum : l) {21 const int i = firstGreaterEqual(r, goal - lSum);22 if (i < r.size()) {23 const int sumPartOne = sum - lSum - r[i];24 const int sumPartTwo = sum - sumPartOne;25 ans = min(ans, abs(sumPartOne - sumPartTwo));26 }27 if (i > 0) {28 const int sumPartOne = sum - lSum - r[i - 1];29 const int sumPartTwo = sum - sumPartOne;30 ans = min(ans, abs(sumPartOne - sumPartTwo));31 }32 }33 }34 35 return ans;36 }37 38 private:39 void dfs(const vector<int>& arr, int i, int count, int path,40 vector<vector<int>>& sums) {41 if (i == arr.size()) {42 sums[count].push_back(path);43 return;44 }45 dfs(arr, i + 1, count + 1, path + arr[i], sums);46 dfs(arr, i + 1, count, path, sums);47 }48 49 int firstGreaterEqual(const vector<int>& arr, int target) {50 return ranges::lower_bound(arr, target) - arr.begin();51 }52};53