給定一個實數陣列,按序排列(從小到大),從陣列從找出若干個數,使得這若干個數的和與M最為接近,描述一個演算法,並給出演算法的複雜度。
阿新 • • 發佈:2019-02-19
有N個正實數(注意是實數,大小升序排列) x1 , x2 ... xN,另有一個實數M。 需要選出若干個x,使這幾個x的和與 M 最接近。 請描述實現演算法,並指出演算法複雜度。
#define M 8 #define N 20 int minDif = INT_MAX; vector<int> minvct; void findCloestNums(int* arr, int step, int len, vector<int> vct, int goalSum, int curSum) { if (!arr || len < 0) { return; } if (minDif > abs(curSum - goalSum)) { minDif = abs(curSum - goalSum); minvct = vct; if (minDif == 0) { return; } } if (step > len) { return; } vct.push_back(arr[step]); findCloestNums(arr, step + 1, len, vct, goalSum, curSum + arr[step]); vct.pop_back(); findCloestNums(arr, step + 1, len, vct, goalSum, curSum); }