PO88前两数之和

PO88前两数之和

思路:回溯+剪枝

#include<vector>
#include<string>
#include<limits.h> 

using namespace std;

class Solution {
public:
    bool backtrack(vector<int>& list, string num, int length, int index, long long sum, int prev) {
        if (index == length) {
            return list.size() >= 3;
        }
        long long curr = 0;
        for (int i = index; i < length; i++) {
            if (i > index && num[index] == ‘0‘) {
                break;
            }
            curr = curr * 10 + num[i] - ‘0‘;
            if (curr > INT_MAX) {
                break;
            }
            if (list.size() >= 2) {
                if (curr < sum) {
                    continue;
                }
                else if (curr > sum) {
                    break;
                }
            }
            list.push_back(curr);
            if (backtrack(list, num, length, i + 1, prev + curr, curr)) {
                return true;
            }
            list.pop_back();
        }
        return false;
    }
};
int main(){
    Solution solution;
    string str;
    cin>>str;
    vector<int>list;
    if(solution.backtrack(list, str, str.length(), 0, 0, 0)){
        cout<<"true"<<endl;
    }else{
        cout<<"false"<<endl;
    }
    return 0;
}

-[1]842. 将数组拆分成斐波那契序列

PO88前两数之和

上一篇:ubuntu20.04不定时卡死,鼠标和键盘都不可用,且tty无效


下一篇:Linux-kill命令参数