def SPN(nums, s):
if s == 0:
# Empty array
return +∞
if nums[s-1] > 0:
# num[s] is admissible, recurse and keep the smallest
return min(nums[s-1], SPN(nums, s-1))
else:
# Just recurse
return SPN(nums, s-1)
print SPN(nums, len(nums)
The c++ version:
#include <vector>
using namespace std;
int rec_min_pos(const vector<int> & nums, int size) {
if (size < 1) {
return INT_MAX;
}
if(nums[size-1] > 0){
return min(nums[size-1], rec_min_pos(nums, size-1));
}
else{
return rec_min_pos(nums, size-1);
}
}
Update:
Assuming that reserving INT_MAX
is not allowed to represent +∞, we can use a negative instead, say -1
, with the convention that min(x,-1) = x
.
Infty= -1 # Conventional +∞
def Min(a, b):
if b == Infty:
return a
else:
return min(a, b)
def SPN(nums, s):
if s == 0:
# Empty array
return Infty
if nums[s-1] > 0:
# num[s] is admissible, recurse and keep the smallest
return Min(nums[s-1], SPN(nums, s-1))
else:
# Just recurse
return SPN(nums, s-1)
That leads us to a more elegant version if we use the convention that any negative value represents +∞:
def Min(a, b):
if a < 0:
return b
if b < 0:
return a
return min(a, b)
def SPN(nums, s):
if s == 1:
return nums[0] # Assumes len(nums) > 0
return Min(nums[s-1], SPN(nums, s-1))
Elegant version in C++:
#include <vector>
using namespace std;
int minimum(int a, int b){
if(a < 0){
return b;
}
if(b < 0){
return a;
}
return min(a, b);
}
int SPN(vector<int> nums, int size){
if(size == 1){
return nums[0];
}
return minimum(nums[size-1], SPN(nums, size-1));
}
21
solved Smallest positive number in a vector recursively