请解释这个递归问题的运行时间

问题描述

首先,我可能只是在编码方面处于中级水平,但对 DS 和 Algo 不太熟悉。

我写了这段代码,它返回数组中给定数量的元素的总和高于某个值,其中:

h : 高度(或每个项目/元素的值)

k : 总和需要大于的值

n_o :原始数组的长度,我在递归过程中减少。

n_a :我的答案数组的长度(存储要考虑其总和的元素组合的数组),我在递归过程中增加

l :要考虑其总和的元素数。

ans : 我的答案数组。

sum(int array[],int length_of_array) :我定义的一个函数,用于在给定长度的情况下查找数组的总和。

void solve(int h[],int k,int n_o,int n_a,int l,int ans[] = {}){
    if(n_a == l){ // base case,if number of elements considered = length of ans array
        int s = sum(ans,n_a); // finds sum of ans[]
        if(s > k){ // checks if sum > defined value
            cout << s;
        }
        cout << endl;
        return;
    }

    for(int i = 0; i < n_o; i++){ // loops through all elements in curent h[]
        int newAns[n_a+1]; // creates a new array which stores the prevIoUs ans[] + a new element from h[]
        for(int j = 0; j < n_a; j++){
            newAns[j] = ans[j];
        }
        newAns[n_a] = h[i];
        //ros stands for rest of string.
        int ros[n_o-i-1]; // creates a new array which stores the new h[] to be passed on.
        for(int j = i+1; j < n_o; j++){
            ros[j-i-1] = h[j];
        }
        solve(ros,k,n_o-i-1,n_a +1,l,newAns);//recursively calls the function.
    }
}

我的输入是:

k = 38

h[] = 20 19 10 8 8 7 7 7

这段代码运行得很好,但它遍历了所有可能的情况并计算了所有可能的总和,但只打印了高于定义值 (k) 的那些。此代码在 VSCode 上的执行时间大约为 1.8 秒。

现在我的想法是,我可以通过减少递归次数来提高效率,只需检查是否有可能在某些元素之后达到总和。例如,对于l=2(只能考虑2个元素),一旦你考虑了20、19,就没有其他元素可以达到总和,然后一旦你考虑了20,从19开始,就没有2个元素的组合达到38.

然后我将代码更新为这个,

void solve(int h[],int ans[] = {}){
    if(n_a == l){
        int s = sum(ans,n_a);
        if(s > k){
            cout << s;
        }
        cout << endl;
        return;
    }

    for(int i = 0; i < n_o; i++){
        //This is the new part.
        int s = 0;
        for(int x = i; x < l-n_a; x++){
            s += h[x];
        }
        if(sum(ans,n_a) + s < k){
            return;
        }
        //upto here
        int newAns[n_a+1];
        for(int j = 0; j < n_a; j++){
            newAns[j] = ans[j];
        }
        newAns[n_a] = h[i];
        int ros[n_o-i-1];
        for(int j = i+1; j < n_o; j++){
            ros[j-i-1] = h[j];
        }
        solve(ros,newAns);
    }
}

这段新代码只检查要考虑的剩余元素数的总和(l - n_a)+现有 ans[] 的总和是否给出大于 k 的值,如果不是,则返回。

虽然 imo 这应该大大减少了执行时间,但程序现在实际上需要更多的时间来执行(在 VSCode 上为 1.8 到 2.5 秒)。

有人能解释一下我出错的原因或地方吗? 另外,如果可能的话,我该如何改进这段代码

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)