給定一個只包含數字的字符串,復原它並返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四個整數(每個整數位於 0 到 255 之間組成),整數之間用 '.' 分隔。
示例:
輸入: "25525511135"
輸出: ["255.255.11.135", "255.255.111.35"]
class Solution {//回溯法
vector<string>res;
string sel;
public:
vector<string> restoreIpAddresses(string s) {
int sSize=s.size();
if(sSize<4||sSize>12)return {};
sel=s;
helper(0,0,"");
return res;
}
void helper(int start,int cnt,string path){//當前下標;當前第幾個分塊;路徑
if(cnt==4)
if(start==sel.size()){//找到
path.pop_back();//去除最後一個點‘.’
res.push_back(path);
return;
}
else return;//越界
for(int i=1;i<=3&&start+i<=sel.size();++i){//依此檢查sel.substr(start,i)是否滿足
if(i==2&&sel[start]=='0')break;//注意!!!兩位數和三位數時,第一位不能爲0
if(i==3&&stoi(sel.substr(start,i))>255)break;//三位數時必須小於256
helper(start+i,cnt+1,path+sel.substr(start,i)+'.');
}
}
};
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回鋸齒形層次遍歷如下:
[
[3],
[20,9],
[15,7]
]
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
if(!root)return {};
deque<TreeNode*>q;
vector<vector<int>>res;
q.push_back(root);
bool front_back=true;//判斷雙端隊列從那一頭開始遍歷,true則首端,false則尾端
while(q.size()){
int qSize=q.size();
vector<int>path;
while(qSize--)
if(front_back){//首端出隊,尾端入隊,入隊順序:左子樹-右子樹
auto temp=q.front();
q.pop_front();
path.push_back(temp->val);
if(temp->left)
q.push_back(temp->left);
if(temp->right)
q.push_back(temp->right);
}
else{//尾端出隊,首端入隊,入隊順序:右子樹-左子樹
auto temp=q.back();
q.pop_back();
path.push_back(temp->val);
if(temp->right)
q.push_front(temp->right);
if(temp->left)
q.push_front(temp->left);
}
front_back=!front_back;
res.push_back(path);
}
return res;
}
};