2020年4月20日

今日算法題 22. 括號生成

數字 n 代表生成括號的對數,請你設計一個函數,用於能夠生成所有可能的並且 有效的 括號組合。
示例:

輸入:n = 3
輸出:[
       "((()))",
       "(()())",
       "(())()",
       "()(())",
       "()()()"
     ]

題解

class Solution {
    //題解中給出的答案;不是很理解,但思路基本清晰了
    public List<String> generateParenthesis(int n) {
		List<String> combinations = new ArrayList();
		generateAll2(new char[2 * n], 0, combinations);
		return combinations;
	}
	
	public static void generateAll2(char[] chars,int opt,List<String> combinations){
		
		if(opt == chars.length){
			if(valid2(chars)){
				combinations.add(new String(chars));
			}
		}else{
			chars[opt] = '(';
			generateAll2(chars,opt+1,combinations);
			chars[opt] = ')';
			generateAll2(chars,opt+1,combinations);
		}
		
		
	}
	
	public static boolean valid2(char[] chars){
		int temp = 0;
		for (int i = 0; i <chars.length  ; i++) {
			if(chars[i] == '('){
				temp++;
			}else{
				temp--;
			}
			if(temp < 0){
				return false;
			}
		}
		return (temp == 0);
	}
}

200 島嶼數量

給你一個由 '1'(陸地)和 '0'(水)組成的的二維網格,請你計算網格中島嶼的數量。

島嶼總是被水包圍,並且每座島嶼只能由水平方向和/或豎直方向上相鄰的陸地連接形成。

此外,你可以假設該網格的四條邊均被水包圍。

示例 1:

輸入:
11110
11010
11000
00000
輸出: 1

示例 2:

輸入:
11000
11000
00100
00011
輸出: 3
解釋: 每座島嶼只能由水平和/或豎直方向上相鄰的陸地連接而成。
Related Topics
  • 深度優先搜索
  • 廣度優先搜索
  • 並查集
  • class Solution {
    	public int numIslands(char[][] grid) {
    		if(null == grid || grid.length == 0 ){
    			return 0;
    		}
    		int result = 0 ;
    		int nc = grid.length;
    		int nr = grid[0].length;
    		for (int i = 0; i < nc ; i++) {
    			for (int j = 0; j < nr ; j++) {
    				if(grid[i][j] == '1'){
    					++result;
    					dfs(grid,i,j);
    				}
    			}
    		}
    		return result;
    	}
    	
    	private void dfs(char[][] grid, int i, int j) {
    		
    		int nc = grid.length;
    		int nr = grid[0].length;
    		if(i<0 || j < 0 || i >= nc || j >= nr || grid[i][j] == '0'){
    			return;
    		}
    		grid[i][j] = '0';
    		dfs(grid,i+1,j);
    		dfs(grid,i-1,j);
    		dfs(grid,i,j+1);
    		dfs(grid,i,j-1);
    	}
    }
    

    8.字符串轉換整數

    //請你來實現一個 atoi 函數,使其能將字符串轉換成整數。 
    //
    // 首先,該函數會根據需要丟棄無用的開頭空格字符,直到尋找到第一個非空格的字符爲止。接下來的轉化規則如下: 
    //
    // 
    // 如果第一個非空字符爲正或者負號時,則將該符號與之後面儘可能多的連續數字字符組合起來,形成一個有符號整數。 
    // 假如第一個非空字符是數字,則直接將其與之後連續的數字字符組合起來,形成一個整數。 
    // 該字符串在有效的整數部分之後也可能會存在多餘的字符,那麼這些字符可以被忽略,它們對函數不應該造成影響。 
    // 
    //
    // 注意:假如該字符串中的第一個非空格字符不是一個有效整數字符、字符串爲空或字符串僅包含空白字符時,則你的函數不需要進行轉換,即無法進行有效轉換。 
    //
    // 在任何情況下,若函數不能進行有效的轉換時,請返回 0 。 
    //
    // 提示: 
    //
    // 
    // 本題中的空白字符只包括空格字符 ' ' 。 
    // 假設我們的環境只能存儲 32 位大小的有符號整數,那麼其數值範圍爲 [−231, 231 − 1]。如果數值超過這個範圍,請返回 INT_MAX (231
    // − 1) 或 INT_MIN (−231) 。 
    // 
    //
    // 
    //
    // 示例 1: 
    //
    // 輸入: "42"
    //輸出: 42
    // 
    //
    // 示例 2: 
    //
    // 輸入: "   -42"
    //輸出: -42
    //解釋: 第一個非空白字符爲 '-', 它是一個負號。
    //     我們儘可能將負號與後面所有連續出現的數字組合起來,最後得到 -42 。
    // 
    //
    // 示例 3: 
    //
    // 輸入: "4193 with words"
    //輸出: 4193
    //解釋: 轉換截止於數字 '3' ,因爲它的下一個字符不爲數字。
    // 
    //
    // 示例 4: 
    //
    // 輸入: "words and 987"
    //輸出: 0
    //解釋: 第一個非空字符是 'w', 但它不是數字或正、負號。
    //     因此無法執行有效的轉換。 
    //
    // 示例 5: 
    //
    // 輸入: "-91283472332"
    //輸出: -2147483648
    //解釋: 數字 "-91283472332" 超過 32 位有符號整數範圍。 
    //     因此返回 INT_MIN (−231) 。
    // 
    // Related Topics 數學 字符串
    
    
    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        //TODO 題解1
    	public static int myAtoi(String str) {
    		if(null == str ||str.trim() == "" ){
    			return 0;
    		}
    		int symbol = 1;
    		Long result = 0L;
    		str = str.trim();
    		for (int i = 0; i < str.length(); i++) {
    			char c = str.charAt(i);
    			if(i == 0 ){
    				if(c == '-'){
    					symbol = -1;
    					continue;
    				}
    				if(c == '+'){
    					continue;
    				}
    			}
    			if(result >= Integer.MAX_VALUE){
    				break;
    			}
    			if(c >= '0' && c <= '9'){
    				result = result * 10 + c-48;
    			}else{
    				break;
    			}
    		}
    		if(result*symbol >= Integer.MAX_VALUE){
    			return Integer.MAX_VALUE;
    		}
    		if(result*symbol <= Integer.MIN_VALUE){
    			return Integer.MIN_VALUE;
    		}
    		
    		return (int) (result*symbol);
    	}
    	
    	public static void main(String[] args) {
    		int i = myAtoi("9223372036854775808");
    		System.out.println(i);
    	}
    	
    	//TODO 題解2
    	public int myAtoi2(String str) {
    		Automaton automaton = new Automaton();
    		for (int i = 0; i < str.length(); i++) {
    			if(automaton.getFlag()){
    				automaton.getInteger(str.charAt(i));
    			} else {
    				break;
    			}
    		}
    		return automaton.getResult();
    	}
    	
    	enum DFA{
    		START,
    		SIGNED,
    		NUMBER,
    		END;
    	}
    	
    	class Automaton{
    		//自動裝配初始狀態
    		private DFA state = DFA.START;
    		
    		//記錄狀態流轉
    		private Map<DFA,DFA[]> map;
    		
    		//記錄符號位
    		private char sign = '+';
    		
    		//記錄結果
    		private int result = 0 ;
    		
    		//判斷終止條件
    		private boolean flag = true;
    		
    		public Automaton(){
    			map = new HashMap<>();
    			map.put(DFA.START,new DFA[]{DFA.START,DFA.SIGNED,DFA.NUMBER,DFA.END});
    			map.put(DFA.SIGNED,new DFA[]{DFA.END,DFA.END,DFA.NUMBER,DFA.END});
    			map.put(DFA.NUMBER,new DFA[]{DFA.END,DFA.END,DFA.NUMBER,DFA.END});
    			map.put(DFA.END,new DFA[]{DFA.END,DFA.END,DFA.END,DFA.END});
    		}
    		public int getResult() {
    			return result;
    		}
    		
    		public boolean getFlag() {
    			return flag;
    		}
    		// 處理狀態變化
    		public int getIndex(char c) {
    			if (c == ' ') return 0;
    			if (c == '+' || c == '-') return 1;
    			if (c >= '0' && c <= '9') return 2;
    			return 3;
    		}
    		
    		//計算當前結果
    		public void getInteger(char c){
    			//跟蹤當前狀態
    			state = map.get(state)[getIndex(c)];
    			switch (state){
    				case NUMBER:
    					if(sign == '+' && (result > Integer.MAX_VALUE/10 || (result == Integer.MAX_VALUE/10 && c - '0' > 7))){
    						result = Integer.MAX_VALUE;
    						flag = false;
    						break;
    					}else if(sign == '-' && (result < Integer.MIN_VALUE/10 || (result == Integer.MIN_VALUE/10 && c - '0' > 8))){
    						result = Integer.MIN_VALUE;
    						flag = false;
    						break;
    					}
    					result = (sign == '+')?(result * 10 + c- '0'):(result * 10 - (c-'0'));
    					break;
    				case SIGNED:
    					sign = c;
    					break;
    				case END:
    					flag = false;
    					break;
    					default:
    						break;
    			}
    		}
    		
    	}
    }
    //leetcode submit region end(Prohibit modification and deletion)
    

    11.盛最多水的容器

    給你 n 個非負整數 a1a2,...,an,每個數代表座標中的一個點 (iai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (iai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

    說明:你不能傾斜容器,且 n 的值至少爲 2。

     

    圖中垂直線代表輸入數組 [1,8,6,2,5,4,8,3,7]。在此情況下,容器能夠容納水(表示爲藍色部分)的最大值爲 49。

     

    示例:

    輸入:[1,8,6,2,5,4,8,3,7]
    輸出:49
    Related Topics
  • 數組
  • 雙指針
  • 題解

    public int maxArea(int[] height) {
    		if(height.length <= 1){
    			return 0;
    		}
    		int maxArea = 0 ;
    		for (int i = 0; i < height.length ; i++) {
    			for (int j = i+1; j < height.length ; j++) {
    				int min = Math.min(height[i],height[j]);
    				maxArea =  Math.max(min * (j-i),maxArea);
    			}
    		}
    		
    		return maxArea;
    	}
    	//雙指針
    	public int maxArea2(int[] height) {
    		if(height.length <= 1){
    			return 0;
    		}
    		int maxArea = 0 ;
    		int l = 0 ,r = height.length -1 ;
    		while (l < r){
    			if(height[l] <= height[r] ){
    				maxArea = Math.max(height[l]*(r-l),maxArea);
    				l++;
    			}else{
    				maxArea = Math.max(height[r]*(r-l),maxArea);
    				r--;
    			}
    		}
    		return maxArea;
    	}
    
    
    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章