c++, both iterative and recursive solutions


  • 2
    1. iterative solution
    class Solution {
    public:
        bool isOneBitCharacter(vector<int>& bits) {
            int i = 0, n = bits.size() - 1;
            while (i < n) i += bits[i] + 1;
            return i == n;
        }
    };
    
    1. recursive solution
    class Solution {
    public:
        bool isOneBitCharacter(vector<int>& bits) {
            return dfs(bits, 0);        
        }
    private:
        bool dfs(vector<int>& bits, int idx) {
            if (idx == bits.size()) return false;
            if (idx == bits.size() - 1 && bits[idx] == 0) return true;
            if (bits[idx] == 1) return dfs(bits, idx + 2);
            else return dfs(bits, idx + 1);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.