Home  >  Article  >  Web Front-end  >  Two algorithmic questions about Yang Hui’s triangle and bracket matching

Two algorithmic questions about Yang Hui’s triangle and bracket matching

一个新手
一个新手Original
2017-09-20 10:30:411259browse

1. Enter a number and determine which row it is in Yang Hui's triangle
Key Points: Two-dimensional array

function fun(item) {
        if(item===1) return 1;        
        var arr = [];        
        for(var i=0;;i++) {
            arr[i] = [];            
            for (var j = 0; j <= i; j++) {                
            if (i == j || j == 0) {
                    arr[i][j] = 1
                } else {
                    arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];                    
                    if(arr[i][j] ==item){                        
                    return i+1;
                    }
                }
            }
        }
    }

2. Enter a series of brackets like this:
Two algorithmic questions about Yang Hui’s triangle and bracket matching

 function check(str) {
        var arr = str.split(&#39;&#39;); // 将传入字符串转化为数组
        var stack = new Array(); // 新建栈,这里我用数组代替
        var aString = &#39;({[]})&#39; ; // 用来匹配的字符串
        var index = -1;          //初始化下标
        for (var i = 0; i < arr.length; i++) {            
        var item = arr[i];            
        if ((index = aString.indexOf(item)) < 3) {   // 将每一项都用aString匹配,下标小于3就是左括号
                // 左括号,入栈
                stack.push(item)
            } else {                //  右括号,栈列表出栈一个元素与之匹配
                var target = stack.pop();                //  如果出栈元素不存在,则这个右括号没有响应匹配的左括号,验证失败
                if (!target) {                    return false
                }                // 取出与 item 对应的左括号与出栈元素匹配,不相等则验证失败
                if (target !== aString.charAt(5-index)) {                    
                return false
                }
            }
        }        //  循环匹配完成后,如果栈列表还有元素,则缺少与之匹配的右括号,验证失败
        if (stack.length) {            
        return false
        }        //  ok
        return true
    }

The above is the detailed content of Two algorithmic questions about Yang Hui’s triangle and bracket matching. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn