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
|
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums);
int minSubArrayLen(int target, vector<int>& nums, int begin, int end, int S);
};
int Solution::minSubArrayLen(int target, vector<int>& nums)
{
int S = accumulate(nums.begin(), nums.end(), 0);
return minSubArrayLen(target, nums, 0, nums.size() - 1, S);
}
int Solution::minSubArrayLen(int target, vector<int>& nums, int begin, int end, int S)
{
if (S < target || begin > end)
return 0;
while (S >= target && begin <= end)
{
if (nums[begin] > nums[end])
{
S = S - nums[end];
--end;
}
else if (nums[begin] < nums[end])
{
S = S - nums[begin];
++begin;
}
else
{
if (begin == end)
return 1;
int left = minSubArrayLen(target, nums, begin + 1, end, S - nums[begin]);
int right = minSubArrayLen(target, nums, begin, end - 1, S - nums[end]);
// left ==0 or right == 0 means that S >= target while S - nums[begin] or S - nums[end] is less than target
return left == 0 || right == 0 ? end - right + 1 : min(left, right);
}
}
return end - begin + 2;
}
| |