在这段代码里值传递与引用传递参数为啥不一样呢

C++语言 码拜 8年前 (2016-04-21) 796次浏览
题目是leetcode第79题,Word Search。
题目:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
[“A”,”B”,”C”,”E”],
[“S”,”F”,”C”,”S”],
[“A”,”D”,”E”,”E”]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
可以AC的代码:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.size()==0 || board[0].size()==0 )
return true;
for(int i=0; i<board.size(); i++)
{
for(int j=0; j<board[0].size(); j++)
{
if(check(board, word, i, j))
return true;
}
}
return false;
}
bool check(vector<vector<char>>&board, string word, int i, int j)
{
if(word.length()==0)
return true;
if(i<0 || j<0 ||i>=board.size() ||j>=board[0].size())
return false;
if(word[0]==board[i][j])
{
char c = word[0];
board[i][j]=0;
if(check(board,word.substr(1), i+1, j)||
check(board,word.substr(1), i-1, j)||
check(board,word.substr(1), i, j+1)||
check(board,word.substr(1), i, j-1))
return true;
else
board[i][j]=c;
}
return false;
}
};
把check函数改成值传递,其他都一样:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(board.size()==0 || board[0].size()==0 )
return true;
for(int i=0; i<board.size(); i++)
{
for(int j=0; j<board[0].size(); j++)
{
if(check(board, word, i, j))
return true;
}
}
return false;
}
bool check(vector<vector<char>>board, string word, int i, int j)
{
if(word.length()==0)
return true;
if(i<0 || j<0 ||i>=board.size() ||j>=board[0].size())
return false;
if(word[0]==board[i][j])
{
char c = word[0];
board[i][j]=0;
if(check(board,word.substr(1), i+1, j)||
check(board,word.substr(1), i-1, j)||
check(board,word.substr(1), i, j+1)||
check(board,word.substr(1), i, j-1))
return true;
else
board[i][j]=c;
}
return false;
}
};
就提示Time limited exceeded,为虾米呢,不科学啊
解决方案

40

值传递会拷贝一次变量,所以相比引用传递效率低,超时了

20

值传递的话二维向量还得拷贝一份传到函数里,要是向量很大拷贝就比较慢了

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明在这段代码里值传递与引用传递参数为啥不一样呢
喜欢 (0)
[1034331897@qq.com]
分享 (0)