首页 > 其他 > 详细

PO88前两数之和

时间:2021-09-15 11:37:00      阅读:23      评论:0      收藏:0      [点我收藏+]

技术分享图片

思路:回溯+剪枝

#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前两数之和

原文:https://www.cnblogs.com/aoke2002/p/15270531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!