vector 踩过的坑

今天,做LeetCode上的一道题,198题:Rob House,在纸上画了画,发现了重复的结构,就使用了递归的方式实现的

 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6 class Solution {
 7 private:
 8     vector<int> memo;
 9     // consider try rob from [index..n-1],it does not mean rob the index house,it just rob from range
10     // [index...n-1]
11     int  tryRob(vector<int>& nums,int index){
12         if(index >= nums.size())
13             return 0;
14         if(memo[index] != -1)
15             return memo[index];
16         int val = 0;
17         for(int i = index;i<nums.size();i++)
18             val = max(val,nums[i] + tryRob(nums,i+2));
19         memo[index] = val;
20         return val;
21     }
22 
23 public:
24     int rob(vector<int>& nums) {
25         for(int i = 0 ; i < nums.size() ; i ++)
26            // memo[i] = -1;
27            // 采坑1
28            // 我们向 vector 中插入元素,是通过push_back()函数,并且注意当vector<int> vec;时,声明的是一个空向量,
29            // 因此,不能采用下标的方式访问元素,只有! !!先通过push_back()函数加入元素后,才能采用下标的方式
30            // 访问元素!!!,但是下标方式仅能对确知已存在的元素进行下标操作。如果使用下标定位元素然后修改,
31            // 只能是修改size以内的元素才能成功.一开始vector为空时,不能对其进行下标赋值。而要用push_back().
32            memo.push_back(-1);
33         return tryRob(nums, 0);
34     }
35 };
36 
37 int main(){
38     vector<int> nums = {2,7,9,3,1};
39     cout<<Solution().rob(nums)<<endl;
40     return 0;
41 }

一开始,运行,不输出结果

我又重新思考了程序的逻辑,觉得没问题,所以想可能是编译的问题,因为,平时对于小程序,我不用IDE的,都是使用Sublime3编辑器的,我把sublime3安装了一些插件,可以编译运行C++,(不过调试功能没配置好,配置完成后,还是有一些问题,找了好久也就没再坚持,毕竟基本上是用来写小的程序而不是大的项目,也不需要调试功能,如果看到这篇博客的同学配置成功的可以告知我,谢谢哦!)也可以写python,markdown等,所以,我直接贴到leetcode 上了,runtime error  : reference binding to null pointer of type 'value_type' ,我才意识到,memo没有初始化,就检索了vector初始化,原来,我一直认定的是错误的,我觉得vector支持迭代器,下标访问,就想当然的认为对一个没经过任何初始化的vector可以使用下标操作。既是教训也是经验。写出来共勉。

其实,这题还可以使用动态规划,上面说了,有重叠子问题

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums){
 4         int n = nums.size();
 5         if(n == 0)
 6             return 0;
 7         // memo[i] : can get the max value if consider rob nums[i...n-1]
 8         vector<int> memo(n,0);
 9         memo[n-1] = nums[n-1];// abvious,nums[n-1,n) has only nums[n-1],
10         //(nums[i...n-1] ,can repretation [i...n))
11         for(int i = n-2;i>=0;i--)
12             for(int j = i;j<n;j++)
13                 //memo[i] = max(memo[i],nums[j] + memo[j+2])
14                 memo[i] = max(memo[i],nums[j] + (j+2<n? memo[j+2]:0));
15         return memo[0];
16     }
17 };

以后遇到坑,会再补充。

猜你喜欢

转载自www.cnblogs.com/Holly-blog/p/9778643.html