今天的刷题的内容是还是关于队列的数据结构和昨天的一致;
今天要讲的是队列和图论算法的应用
leetcode 279:
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n.For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
. 返回一个数由完全平方数和构成的最小的长度。 数学建模过程,假设有n个结点,如果两个结点之间相差一个完全平方数,那么在这两个数之间就连接一条边,构成一个图,就将原问题转换为求救图中的最短路径的问题,或者说是广度优先的算法;
class Solution {
public:
int numSquares(int n) {
int step=0;//建模实现,将所有节点:如果两个结点之间的数据差相差一个完全平方数,那么就在两个数据之间构造一条边
queue<pair<int ,int>> node;//第二个int表示的是行走的步数;
vector<bool> flag(n+1,false);//如果这个节点被访问过,那么下次不再进行访问;
node.push(make_pair(n,step));
while(!node.empty()){
pair<int,int> top=node.front();
step=top.second;
int nums=top.first;
node.pop();
if(nums==0){//如果数值为0,说明已经到达到达了,所以返回结果,step步数;
return step;
}
for(int i=1;nums-i*i>=0;i++){
if(flag[nums-i*i]==false){
node.push(make_pair(nums-i*i,step+1));
flag[nums-i*i]=true;
}
}
}
return step;
}
};
同理解法类似的还有leetcode127:
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
//使用一个队列来维护信息;
int step=1;
queue<pair<string,int>> strNode;
strNode.push(make_pair(beginWord,step));
int size=wordList.size();
vector<bool> flag(size+1,false);
while(!strNode.empty()){
pair<string,int> top=strNode.front();
strNode.pop();
string firstStr=top.first;
int step=top.second;
if(firstStr==endWord){
return step;
}
for(int i=0;i<size;i++){
if(flag[i]==false){
string temp=wordList[i];
if(compare(firstStr,temp)){
//如果他们之间相差一个字符,那么返回true
strNode.push(make_pair(temp,step+1));
flag[i]=true;
}
}
}
}
return 0;}
private:
bool compare(string& s1,string &s2){
if(s1.size()!=s2.size()){
return false;
}
int count=0;
for(int i=0;i<s1.size();i++){
if(s1[i]!=s2[i]){
count++;
}
}
if(count==1){
return true;
}
return false;
}
};