数组越界问题(C++)

错误信息:
Line 1034: Char 34: runtime error: addition of unsigned offset to 0x603000000040 overflowed to 0x60300000003c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/…/lib/gcc/x86_64-linux-gnu/9/…/…/…/…/include/c++/9/bits/stl_vector.h:1043:34
代码:

class Solution {	//40. 组合总和 II
public:
	vector<vector<int>> result;
	vector<int> path;
	int sum = 0;
	void backtracking(vector<int>& candidates, int target, int startIndex, vector<bool>& used) {
		if (sum == target) {
			result.push_back(path);
			return;
		}
		for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; ++i) {
			//used[i-1]=true表示同一树枝candidates[i-1]使用过
			//used[i-1]=false表示同一树层candidates[i-1]使用过
			if (i >= 0 && candidates[i] == candidates[i - 1] && used[i-1]==false)continue;	//这里要注意i-1>=0,所以i>0 
			sum += candidates[i];
			path.push_back(candidates[i]);
			used[i] = true;		//表示同一树枝candidates[i]使用过
			backtracking(candidates, target, i + 1, used);
			used[i] = false;	//表示同一树层candidates[i]使用过
			sum -= candidates[i];
			path.pop_back();
		}
	}
	vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
		vector<bool> used(candidates.size(), false);
		sort(candidates.begin(), candidates.end());
		backtracking(candidates, target, 0, used);
		return result;
	}
};

overflowed表示溢出,看见这样的信息就要想到是不是有数组发生了越界,去查看数组,发现在if判断里把i>0写成了i>=0。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海螺蜜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值