173. 二叉搜索樹迭代器;劍指 Offer 38. 字符串的排列

實現一個二叉搜索樹迭代器。你將使用二叉搜索樹的根節點初始化迭代器。

調用 next() 將返回二叉搜索樹中的下一個最小的數。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
    stack<TreeNode*>s;
    TreeNode *cur;
public:
    BSTIterator(TreeNode* root) {
        this->cur=root;
    }
    
    /** @return the next smallest number */
    int next() {
        int res=INT_MAX;
        while(cur||s.size()){
            while(cur){
                s.push(cur);
                cur=cur->left;
            }
            cur=s.top();
            res=cur->val;
            s.pop();
            cur=cur->right;
            break;
        }
        return res;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return cur||s.size();
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */

 

輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。

輸入描述:

輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。
class Solution {
    vector<string> res;
    string sel,path;
    bitset<9>b;
public:
    vector<string> Permutation(string str) {
        if(str.size()==0)return {};
        sel=str;
        sort(sel.begin(),sel.end());
        backTrack();
        return res;
    }
    void backTrack(){
        if(path.size()==sel.size()){
            res.push_back(path);
            return ;
        }
        for(int i=0;i<sel.size();++i){
            if(b[i])continue;
            if(i>0&&!b[i-1]&&sel[i]==sel[i-1])continue;//去重最關鍵!!!
            path.push_back(sel[i]);
            b[i]=1;
            backTrack();
            b[i]=0;
            path.pop_back();
        }
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章