why my code arouse free(): invalid pointer: 0x000000000120df00 ***


  • 0
    D

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
    vector<vector<int> > result ;
    if(candidates.size() == 0 )
    {
    return result;
    }
    sort(candidates.begin(), candidates.end());
    vector<int> tmp_memo;
    vector<int> tmp_index;
    int tmp_target = target;
    for(int i = candidates.size() - 1; i >=0; i --)
    {
    tmp_index.push_back(i);
    }
    while( !tmp_index.empty() )
    {
    int index = tmp_index.back();
    //查看有没有越界
    if(index >= candidates.size() )
    {
    tmp_index.pop_back();
    int i = tmp_index.back();
    //父结点出栈
    tmp_index.pop_back();
    tmp_memo.pop_back();
    tmp_target += candidates[i];
    continue;
    }
    //没有越界就访问
    tmp_memo.push_back(candidates[index]);
    if(tmp_target == candidates[index])//找到目标
    {
    result.push_back(tmp_memo);
    if(tmp_memo.size() == 1)//只有一个值,表明是顶层结点了,所以直接break
    {
    break;
    }
    //当前结点出栈
    tmp_index.pop_back();
    tmp_memo.pop_back();

                //tmp_target += candidates[index];
                int i = tmp_index.back();
                //父结点出栈
                tmp_index.pop_back();
                tmp_memo.pop_back();
                //目标值要加回去
                tmp_target += candidates[i];
                //父结点的右兄弟入栈
                tmp_index.push_back(i+1);
            }
            else if(tmp_target < candidates[index])//后面的candidate更大,没有寻找的必要
            {
                if(tmp_memo.size() == 1)//只有一个值,表明是顶层结点了,所以直接break
                {
                    break;
                }
                //当前结点出栈,
                tmp_index.pop_back();
                tmp_memo.pop_back();
                //tmp_target += candidates[index];
                //父结点出栈
                int i = tmp_index.back();
                tmp_index.pop_back();
                tmp_memo.pop_back();
                tmp_target += candidates[i];
                //父结点的右兄弟入栈
                tmp_index.push_back(i+1);
            }
            else
            {
                //
                tmp_target -= candidates[index];
                //推入下一层的孩子结点
                tmp_index.push_back(index);
            }
        }
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.