Parantheses

1. Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

方法:利用integer的特性,代替Stack,节约了extra space! (不记得从哪里看来的,觉得想法很好!)

代码:

public class Solution {
	public boolean isValid(String s) {
		long result = 0;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			int val = 0;
			switch (c) {
			case '(':
				val = 1;
				break;
			case ')':
				val = -1;
				break;
			case '[':
				val = 2;
				break;
			case ']':
				val = -2;
				break;
			case '{':
				val = 3;
				break;
			case '}':
				val = -3;
				break;
			}

			if (val > 0) {
				result = result * 10 + val;
			} else {
				if ((result % 10 + val) != 0)
					return false;
				result = result / 10;
			}
		}
		if (result > 0)
			return false;
		else
			return true;
	}
}


2. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

方法: DFS

时间复杂度: O(2^n)


public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        char[] str = new char[n*2];
        ArrayList<String> list = new ArrayList<String>();
        addParen(list, n, n, str, 0);
        return list;
        
    }
    
    // list: 存所有的结果
    // str: 当前的str
    // index: index of str
    private void addParen(ArrayList<String> list, int leftRem, int rightRem, char[] str, int index){
        if(leftRem < 0 || rightRem < 0)
            return;
        
        if(leftRem == 0 && rightRem == 0){
            String s = String.copyValueOf(str);
            list.add(s);
        }else{
            // 添加左括号
            if(leftRem > 0){
                str[index] = '(';
                addParen(list, leftRem-1, rightRem, str, index+1);
            }
            
            // 添加右括号
            if(rightRem > 0){
                str[index] = ')';
                addParen(list, leftRem, rightRem-1, str, index+1);
            }
        }
    }
}



你可能感兴趣的:(LeetCode)