├── Algorithms ├── 001. Two Sum │ ├── Solution.java │ └── Solution.py ├── 002. Add Two Numbers │ ├── Solution.java │ └── Solution.py ├── 003. Longest Substring Without Repeating Characters │ ├── Solution.java │ └── Solution.py ├── 006. ZigZag Conversion │ ├── Solution.java │ └── Solution.py ├── 007. Reverse Integer │ ├── Solution.java │ └── Solution.py ├── 008. String to Integer (atoi) │ └── Solution.java ├── 009. Palindrome Number │ ├── Solution.java │ └── Solution.py ├── 010. Regular Expression Matching │ └── Solution.java ├── 011. Container With Most Water │ └── Solution.java ├── 012. Integer to Roman │ ├── Solution.java │ └── Solution.py ├── 013. Roman to Integer │ ├── Solution.java │ └── Solution.py ├── 014. Longest Common Prefix │ ├── Solution.java │ └── Solution.py ├── 015. 3Sum │ ├── Solution.java │ └── Solution.py ├── 016. 3Sum Closest │ └── Solution.java ├── 017. Letter Combinations of a Phone Number │ ├── Solution.java │ └── Solution.py ├── 018. 4Sum │ └── Solution.java ├── 019. Remove Nth Node From End of List │ ├── Solution.java │ └── Solution.py ├── 020. Valid Parentheses │ └── Solution.java ├── 021. Merge Two Sorted Lists │ ├── Solution.java │ └── Solution.py ├── 022. Generate Parentheses │ ├── Solution.java │ └── Solution.py ├── 023. Merge k Sorted Lists │ ├── Solution.java │ └── Solution.py ├── 024. Swap Nodes in Pairs │ ├── Solution.java │ └── Solution.py ├── 025. Reverse Nodes in k-Group │ └── Solution.java ├── 026. Remove Duplicates from Sorted Array │ ├── Solution.java │ └── Solution.py ├── 027. Remove Element │ ├── Solution.java │ └── Solution.py ├── 028. Implement strStr() │ └── Solution.java ├── 029. Divide Two Integers │ └── Solution.java ├── 031. Next Permutation │ ├── Solution.java │ └── Solution.py ├── 032. Longest Valid Parentheses │ └── Solution.java ├── 033. Search in Rotated Sorted Array │ └── Solution.java ├── 034. Search for a Range │ ├── Solution.java │ └── Solution.py ├── 035. Search Insert Position │ ├── Solution.java │ └── Solution.py ├── 036. Valid Sudoku │ └── Solution.java ├── 037. Sudoku Solver │ └── Solution.java ├── 038. Count and Say │ └── Solution.java ├── 039. Combination Sum │ ├── Solution.java │ └── Solution.py ├── 040. Combination Sum II │ └── Solution.java ├── 041. First Missing Positive │ ├── Solution.java │ └── Solution.py ├── 042. Trapping Rain Water │ └── Solution.java ├── 043. Multiply Strings │ ├── Solution.java │ └── Solution.py ├── 045. Jump Game II │ └── Solution.java ├── 046. Permutations │ ├── Solution.java │ └── Solution.py ├── 047. Permutations II │ ├── Solution.java │ └── Solution.py ├── 048. Rotate Image │ ├── Solution.java │ └── Solution.py ├── 049. Group Anagrams │ ├── Solution.java │ └── Solution.py ├── 050. Pow(x, n) │ ├── Solution.java │ └── Solution.py ├── 051. N-Queens │ ├── Solution.java │ └── Solution.py ├── 052. N-Queens II │ ├── Solution.java │ └── Solution.py ├── 053. Maximum Subarray │ ├── Solution.java │ └── Solution.py ├── 054. Spiral Matrix │ ├── Solution.java │ └── Solution.py ├── 055. Jump Game │ ├── Solution.java │ └── Solution.py ├── 056. Merge Intervals │ └── Solution.java ├── 057. Insert Interval │ ├── Solution.java │ └── Solution.py ├── 058. Length of Last Word │ ├── Solution.java │ └── Solution.py ├── 059. Spiral Matrix II │ ├── Solution.java │ └── Solution.py ├── 060. Permutation Sequence │ ├── Solution.java │ └── Solution.py ├── 061. Rotate List │ ├── Solution.java │ └── Solution.py ├── 062. Unique Paths │ ├── Solution.java │ └── Solution.py ├── 063. Unique Paths II │ ├── Solution.java │ └── Solution.py ├── 064. Minimum Path Sum │ ├── Solution.java │ └── Solution.py ├── 066. Plus One │ └── Solution.java ├── 067. Add Binary │ ├── Solution.java │ └── Solution.py ├── 068. Text Justification │ ├── Solution.java │ └── Solution.py ├── 069. Sqrt(x) │ ├── Solution.java │ └── Solution.py ├── 070. Climbing Stairs │ ├── Solution.java │ └── Solution.py ├── 072. Edit Distance │ ├── Solution.java │ └── Solution.py ├── 073. Set Matrix Zeroes │ ├── Solution.java │ └── Solution.py ├── 074. Search a 2D Matrix │ ├── Solution.java │ └── Solution.py ├── 075. Sort Colors │ ├── Solution.java │ └── Solution.py ├── 077. Combinations │ ├── Solution.java │ └── Solution.py ├── 078. Subsets │ ├── Solution.java │ └── Solution.py ├── 079. Word Search │ └── Solution.java ├── 080. Remove Duplicates from Sorted Array II │ ├── Solution.java │ └── Solution.py ├── 081. Search in Rotated Sorted Array II │ └── Solution.java ├── 082. Remove Duplicates from Sorted List II │ ├── Solution.java │ └── Solution.py ├── 083. Remove Duplicates from Sorted List │ ├── Solution.java │ └── Solution.py ├── 086. Partition List │ ├── Solution.java │ └── Solution.py ├── 087. Scramble String │ ├── Solution.java │ └── Solution.py ├── 088. Merge Sorted Array │ ├── Solution.java │ └── Solution.py ├── 089. Gray Code │ ├── Solution.java │ └── Solution.py ├── 090. Subsets II │ ├── Solution.java │ └── Solution.py ├── 091. Decode Ways │ ├── Solution.java │ └── Solution.py ├── 092. Reverse Linked List II │ └── Solution.java ├── 093. Restore IP Addresses │ ├── Solution.java │ └── Solution.py ├── 094. Binary Tree Inorder Traversal │ ├── Solution.java │ └── Solution.py ├── 095. Unique Binary Search Trees II │ └── Solution.java ├── 096. Unique Binary Search Trees │ ├── Solution.java │ └── Solution.py ├── 097. Interleaving String │ ├── Solution.java │ └── Solution.py ├── 098. Validate Binary Search Tree │ ├── Solution.java │ └── Solution.py ├── 099. Recover Binary Search Tree │ └── Solution.py └── 100. Same Tree │ ├── Solution.java │ └── Solution.py ├── README.md ├── java ├── 001. Two Sum.java ├── 002. Add Two Numbers.java ├── 003. Longest Substring Without Repeating Characters.java ├── 006. ZigZag Conversion.java ├── 007. Reverse Integer.java ├── 008. String to Integer (atoi).java ├── 009. Palindrome Number.java ├── 010. Regular Expression Matching.java ├── 011. Container With Most Water.java ├── 012. Integer to Roman.java ├── 013. Roman to Integer.java ├── 014. Longest Common Prefix.java ├── 015. 3Sum.java ├── 016. 3Sum Closest.java ├── 017. Letter Combinations of a Phone Number.java ├── 018. 4Sum.java ├── 019. Remove Nth Node From End of List.java ├── 020. Valid Parentheses.java ├── 021. Merge Two Sorted Lists.java ├── 022. Generate Parentheses.java ├── 023. Merge k Sorted Lists.java ├── 024. Swap Nodes in Pairs.java ├── 025. Reverse Nodes in k-Group.java ├── 026. Remove Duplicates from Sorted Array.java ├── 027. Remove Element.java ├── 028. Implement strStr().java ├── 029. Divide Two Integers.java ├── 031. Next Permutation.java ├── 032. Longest Valid Parentheses.java ├── 033. Search in Rotated Sorted Array.java ├── 034. Search for a Range.java ├── 035. Search Insert Position.java ├── 036. Valid Sudoku.java ├── 037. Sudoku Solver.java ├── 038. Count and Say.java ├── 039. Combination Sum.java ├── 040. Combination Sum II.java ├── 041. First Missing Positive.java ├── 042. Trapping Rain Water.java ├── 043. Multiply Strings.java ├── 045. Jump Game II.java ├── 046. Permutations.java ├── 047. Permutations II.java ├── 048. Rotate Image.java ├── 049. Group Anagrams.java ├── 050. Pow(x, n).java ├── 051. N-Queens.java ├── 052. N-Queens II.java ├── 053. Maximum Subarray.java ├── 054. Spiral Matrix.java ├── 055. Jump Game.java ├── 056. Merge Intervals.java ├── 057. Insert Interval.java ├── 058. Length of Last Word.java ├── 059. Spiral Matrix II.java ├── 060. Permutation Sequence.java ├── 061. Rotate List.java ├── 062. Unique Paths.java ├── 063. Unique Paths II.java ├── 064. Minimum Path Sum.java ├── 066. Plus One.java ├── 067. Add Binary.java ├── 068. Text Justification.java ├── 069. Sqrt(x).java ├── 070. Climbing Stairs.java ├── 072. Edit Distance.java ├── 073. Set Matrix Zeroes.java ├── 074. Search a 2D Matrix.java ├── 075. Sort Colors.java ├── 077. Combinations.java ├── 078. Subsets.java ├── 079. Word Search.java ├── 080. Remove Duplicates from Sorted Array II.java ├── 081. Search in Rotated Sorted Array II.java ├── 082. Remove Duplicates from Sorted List II.java ├── 083. Remove Duplicates from Sorted List.java ├── 086. Partition List.java ├── 087. Scramble String.java ├── 088. Merge Sorted Array.java ├── 089. Gray Code.java ├── 090. Subsets II.java ├── 091. Decode Ways.java ├── 092. Reverse Linked List II.java ├── 093. Restore IP Addresses.java ├── 094. Binary Tree Inorder Traversal.java ├── 095. Unique Binary Search Trees II.java ├── 096. Unique Binary Search Trees.java ├── 097. Interleaving String.java ├── 098. Validate Binary Search Tree.java └── 100. Same Tree.java ├── python ├── 001. Two Sum.py ├── 002. Add Two Numbers.py ├── 003. Longest Substring Without Repeating Characters.py ├── 006. ZigZag Conversion.py ├── 007. Reverse Integer.py ├── 009. Palindrome Number.py ├── 012. Integer to Roman.py ├── 013. Roman to Integer.py ├── 014. Longest Common Prefix.py ├── 015. 3Sum.py ├── 017. Letter Combinations of a Phone Number.py ├── 019. Remove Nth Node From End of List.py ├── 021. Merge Two Sorted Lists.py ├── 022. Generate Parentheses.py ├── 023. Merge k Sorted Lists.py ├── 024. Swap Nodes in Pairs.py ├── 026. Remove Duplicates from Sorted Array.py ├── 027. Remove Element.py ├── 031. Next Permutation.py ├── 034. Search for a Range.py ├── 035. Search Insert Position.py ├── 039. Combination Sum.py ├── 041. First Missing Positive.py ├── 043. Multiply Strings.py ├── 046. Permutations.py ├── 047. Permutations II.py ├── 048. Rotate Image.py ├── 049. Group Anagrams.py ├── 050. Pow(x, n).py ├── 051. N-Queens.py ├── 052. N-Queens II.py ├── 053. Maximum Subarray.py ├── 054. Spiral Matrix.py ├── 055. Jump Game.py ├── 057. Insert Interval.py ├── 058. Length of Last Word.py ├── 059. Spiral Matrix II.py ├── 060. Permutation Sequence.py ├── 061. Rotate List.py ├── 062. Unique Paths.py ├── 063. Unique Paths II.py ├── 064. Minimum Path Sum.py ├── 067. Add Binary.py ├── 068. Text Justification.py ├── 069. Sqrt(x).py ├── 070. Climbing Stairs.py ├── 072. Edit Distance.py ├── 073. Set Matrix Zeroes.py ├── 074. Search a 2D Matrix.py ├── 075. Sort Colors.py ├── 077. Combinations.py ├── 078. Subsets.py ├── 080. Remove Duplicates from Sorted Array II.py ├── 082. Remove Duplicates from Sorted List II.py ├── 083. Remove Duplicates from Sorted List.py ├── 086. Partition List.py ├── 087. Scramble String.py ├── 088. Merge Sorted Array.py ├── 089. Gray Code.py ├── 090. Subsets II.py ├── 091. Decode Ways.py ├── 093. Restore IP Addresses.py ├── 094. Binary Tree Inorder Traversal.py ├── 096. Unique Binary Search Trees.py ├── 097. Interleaving String.py ├── 098. Validate Binary Search Tree.py ├── 099. Recover Binary Search Tree.py └── 100. Same Tree.py └── util ├── csdn.py └── spider.py /Algorithms/001. Two Sum/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] twoSum(int[] numbers, int target) { 3 | int[] res = new int[2]; 4 | Map map = new HashMap(); 5 | for(int i = 0; i < numbers.length; i++){ 6 | map.put(numbers[i], i); 7 | } 8 | for(int i = 0; i < numbers.length; i++){ 9 | int gap = target - numbers[i]; 10 | if(map.get(gap)!= null && (int)map.get(gap)!= i){ 11 | res[0] = i+1; 12 | res[1] = (int)map.get(gap) + 1; 13 | break; 14 | } 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /Algorithms/001. Two Sum/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def twoSum(self, nums, target): 5 | map={} 6 | for i in range(nums.__len__()): 7 | map[(target-nums[i])]=i 8 | for i in range(nums.__len__()): 9 | if(map.get(nums[i])): 10 | ans=[] 11 | ans.append(i+1) 12 | ans.append(map.get(nums[i])+1) 13 | return ans 14 | -------------------------------------------------------------------------------- /Algorithms/002. Add Two Numbers/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 | return add(l1,l2,true); 12 | } 13 | public ListNode add(ListNode l1, ListNode l2,boolean flag) { 14 | boolean a=l1==null; 15 | boolean b=l2==null; 16 | if (a&&b&&flag) { 17 | return null; 18 | } 19 | int val=(a?0:l1.val)+(b?0:l2.val)+(flag?0:1); 20 | int v=val%10; 21 | boolean f=(v==val); 22 | ListNode answer=new ListNode(v); 23 | answer.next=add(a?null:l1.next,b?null:l2.next,f); 24 | return answer; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/002. Add Two Numbers/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | class ListNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.next = None 8 | 9 | class Solution(object): 10 | def addTwoNumbers(self, l1, l2): 11 | return Solution().addTwo(l1,l2,False) 12 | def addTwo(self,l1,l2,flag): 13 | t=False 14 | val=0; 15 | if(l1): 16 | val+=l1.val 17 | t=True 18 | if(l2): 19 | val+=l2.val 20 | t=True 21 | if(flag): 22 | val+=1 23 | t=True 24 | if(val>=10): 25 | flag=True 26 | val-=10 27 | else : 28 | flag=False 29 | if(t): 30 | ans=ListNode(val) 31 | ans.next=Solution().addTwo(l1.next if l1 else None ,l2.next if l2 else None,flag) 32 | return ans 33 | else : 34 | return None 35 | 36 | 37 | a=ListNode(0) 38 | b=ListNode(0) 39 | sol=Solution() 40 | print sol.addTwoNumbers(a,b) -------------------------------------------------------------------------------- /Algorithms/003. Longest Substring Without Repeating Characters/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLongestSubstring(String s) { 3 | int answer=0; 4 | Map map=new HashMap(); 5 | List list=new LinkedList(); 6 | for (int i = 0; i < s.length(); i++) { 7 | String k=s.substring(i, i+1); 8 | if (map.get(k) != null) { 9 | int n=map.get(k)-map.get(list.get(0))+1; 10 | for (int j = 0; j < n; j++) { 11 | map.remove(list.get(0)); 12 | list.remove(0); 13 | } 14 | } 15 | map.put(k, i); 16 | list.add(k); 17 | if (list.size()>answer) { 18 | answer=list.size(); 19 | } 20 | } 21 | return answer; 22 | } 23 | } -------------------------------------------------------------------------------- /Algorithms/003. Longest Substring Without Repeating Characters/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def lengthOfLongestSubstring(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | if(s.__len__()==0): 10 | return 0 11 | map={} 12 | max=0 13 | begin=0 14 | for i in range(s.__len__()): 15 | if(map.get(s[i])!=None): 16 | if(i-begin>max): 17 | max=i-begin 18 | if(map.get(s[i])+1>begin): 19 | begin=map.get(s[i])+1 20 | map[s[i]]=i 21 | print begin 22 | if(s.__len__()-begin>max): 23 | max=s.__len__()-begin 24 | return max 25 | s="abcb" 26 | print Solution().lengthOfLongestSubstring(s) -------------------------------------------------------------------------------- /Algorithms/006. ZigZag Conversion/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String convert(String s, int numRows) { 3 | if(numRows==1){ 4 | return s; 5 | }else{ 6 | int k=numRows*2-2; 7 | String[] res=new String[numRows]; 8 | for (int i = 0; i < res.length; i++) { 9 | res[i]=""; 10 | } 11 | int step=0; 12 | int j=0; 13 | for (int i = 0; i < s.length(); i++) { 14 | step++; 15 | if (step<=numRows) { 16 | j=step; 17 | }else { 18 | j=numRows-(step-numRows); 19 | } 20 | res[j-1]+=s.substring(i, i+1); 21 | if (step==k) { 22 | step=0; 23 | } 24 | } 25 | String result=""; 26 | for (int i = 0; i < res.length; i++) { 27 | result+=res[i]; 28 | } 29 | return result; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Algorithms/006. ZigZag Conversion/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def convert(self, s, numRows): 5 | """ 6 | :type s: str 7 | :type numRows: int 8 | :rtype: str 9 | """ 10 | if(s.__len__()==0): 11 | return '' 12 | if(numRows==1): 13 | return s 14 | n=2*numRows-2 15 | ans=[] 16 | for i in range(numRows): 17 | a=[] 18 | ans.append(a) 19 | for i in range(s.__len__()): 20 | k=i%n 21 | if(k0 ; i--) { 8 | r+=str.substring(i,i+1); 9 | } 10 | r="-"+r; 11 | }else { 12 | for (int i = str.length()-1; i >-1 ; i--) { 13 | r+=str.substring(i,i+1); 14 | } 15 | } 16 | try { 17 | re=Integer.parseInt(r); 18 | 19 | } catch (Exception e) { 20 | 21 | } 22 | return re; 23 | } 24 | } -------------------------------------------------------------------------------- /Algorithms/007. Reverse Integer/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def reverse(self, x): 5 | """ 6 | :type x: int 7 | :rtype: int 8 | """ 9 | if(x==0): 10 | return 0 11 | flag=False 12 | if(x<0): 13 | flag=True 14 | x=0-x 15 | ans=0 16 | while x!=0: 17 | ans=10*ans+x%10 18 | x/=10 19 | print ('ans',ans) 20 | if(flag): 21 | ans=0-ans 22 | if(ans>2147483647 or ans<-2147483648): 23 | return 0 24 | return ans 25 | 26 | 27 | x=1000 28 | print str(x).strip('0')[::-1] if x>0 else '-'+str(-x).strip('0')[::-1] 29 | -------------------------------------------------------------------------------- /Algorithms/008. String to Integer (atoi)/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int myAtoi(String str) { 3 | char[] cs=str.toCharArray(); 4 | long ans=0; 5 | int sign=1; 6 | boolean signFlag=true; 7 | int i=0; 8 | boolean zeroFlag=true; 9 | while (i < cs.length) { 10 | if (zeroFlag) { 11 | while (cs[i]==' ') { 12 | i++; 13 | } 14 | zeroFlag=false; 15 | } 16 | if (!zeroFlag&&cs[i]==' ') { 17 | break; 18 | } 19 | if (cs[i]=='-'||cs[i]=='+') { 20 | if (signFlag) { 21 | sign=44-cs[i]; 22 | signFlag=false; 23 | }else{ 24 | return 0; 25 | } 26 | }else if(cs[i]>='0'&&cs[i]<='9'){ 27 | ans=10*ans+cs[i]-48; 28 | if (sign==1&&ans>=Integer.MAX_VALUE) { 29 | return Integer.MAX_VALUE; 30 | } 31 | if (sign==-1&&ans-1>=Integer.MAX_VALUE) { 32 | return Integer.MIN_VALUE; 33 | } 34 | }else{ 35 | break; 36 | } 37 | i++; 38 | } 39 | return (int) (ans*sign); 40 | } 41 | } -------------------------------------------------------------------------------- /Algorithms/009. Palindrome Number/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(int x) { 3 | if (x < 0) { 4 | return false; 5 | } 6 | int n = x; 7 | int a = 0; 8 | int p = 1; 9 | while (x != 0) { 10 | x /= 10; 11 | a++; 12 | p *= 10; 13 | if (a==1) { 14 | p/=10; 15 | } 16 | } 17 | int b = a / 2; 18 | if (b == 0) { 19 | return true; 20 | } 21 | 22 | for (int i = 0; i < b; i++) { 23 | int begin = n / p; 24 | int end = n % 10; 25 | if (begin != end) { 26 | return false; 27 | } else { 28 | n = n - (begin * p); 29 | p /= 100; 30 | n = (n - end) / 10; 31 | } 32 | } 33 | return true; 34 | } 35 | } -------------------------------------------------------------------------------- /Algorithms/009. Palindrome Number/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def isPalindrome(self, x): 5 | """ 6 | :type x: int 7 | :rtype: bool 8 | """ 9 | return str(x)==str(x)[::-1] -------------------------------------------------------------------------------- /Algorithms/011. Container With Most Water/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | int left=0; 4 | int right=height.length-1; 5 | int ans=(right-left)*Math.min(height[left], height[right]); 6 | while (right>left) { 7 | int water=(right-left)*Math.min(height[left], height[right]); 8 | if (water>ans) { 9 | ans=water; 10 | } 11 | if (height[left]len(str2): 18 | return self.findSameWord(str2,str1) 19 | l=len(str1) 20 | if l==0: 21 | return '' 22 | ans='' 23 | for i in range(l): 24 | if str1[i]==str2[i]: 25 | ans+=str1[i] 26 | else: 27 | break 28 | return ans -------------------------------------------------------------------------------- /Algorithms/015. 3Sum/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | List> ans=new ArrayList>(); 3 | public List> threeSum(int[] nums) { 4 | Arrays.sort(nums); 5 | if (nums.length<3) { 6 | return ans; 7 | } 8 | int length=nums.length; 9 | for (int i = 0; i < length-2; i++) { 10 | if (i==0||nums[i]!=nums[i-1]) { 11 | f(nums,nums[i],i+1,length-1); 12 | } 13 | } 14 | return ans; 15 | } 16 | public void f(int[] nums,int target,int s,int e){ 17 | while (s list=new ArrayList(); 21 | list.add(target); 22 | list.add(nums[s]); 23 | list.add(nums[e]); 24 | ans.add(list); 25 | while (s0 else [] 19 | def f(self,string,state): 20 | for v in self.keyboard.get(string[0]): 21 | if len(string)==1: 22 | yield v 23 | else: 24 | for result in self.f(string[1:],state+v): 25 | yield v+result -------------------------------------------------------------------------------- /Algorithms/019. Remove Nth Node From End of List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode removeNthFromEnd(ListNode head, int n) { 11 | List list=new ArrayList(); 12 | list=addlist(head, list); 13 | if (list.size()==n) { 14 | return head.next; 15 | } 16 | list.get(list.size()-n-1).next=n==1?null:list.get(list.size()-n+1); 17 | return head; 18 | } 19 | public List addlist(ListNode head, List list){ 20 | if (head!=null) { 21 | list.add(head); 22 | }else { 23 | return list; 24 | } 25 | return addlist(head.next, list); 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms/019. Remove Nth Node From End of List/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | # class ListNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def removeNthFromEnd(self, head, n): 11 | """ 12 | :type head: ListNode 13 | :type n: int 14 | :rtype: ListNode 15 | """ 16 | array=[] 17 | while head: 18 | array.append(head) 19 | head=head.next 20 | if n==1: 21 | if len(array)==1: 22 | return None 23 | else: 24 | array[-2].next=None 25 | else: 26 | array[-n].val=array[-n].next.val 27 | array[-n].next=array[-n].next.next 28 | return array[0] -------------------------------------------------------------------------------- /Algorithms/021. Merge Two Sorted Lists/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 | if (l1==null) { 12 | return l2; 13 | } 14 | if (l2==null) { 15 | return l1; 16 | } 17 | ListNode l=null; 18 | if (l1.val>l2.val) { 19 | l=new ListNode(l2.val); 20 | l.next=mergeTwoLists(l1,l2.next); 21 | }else { 22 | l=new ListNode(l1.val); 23 | l.next=mergeTwoLists(l1.next,l2); 24 | } 25 | return l; 26 | } 27 | } -------------------------------------------------------------------------------- /Algorithms/021. Merge Two Sorted Lists/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | # class ListNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def mergeTwoLists(self, l1, l2): 11 | """ 12 | :type l1: ListNode 13 | :type l2: ListNode 14 | :rtype: ListNode 15 | """ 16 | if l1 is None: 17 | return l2 18 | if l2 is None: 19 | return l1 20 | ans=None 21 | if l1.val<=l2.val: 22 | ans=l1 23 | ans.next=self.mergeTwoLists(l1.next,l2) 24 | else: 25 | ans=l2 26 | ans.next=self.mergeTwoLists(l1,l2.next) 27 | return ans -------------------------------------------------------------------------------- /Algorithms/022. Generate Parentheses/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def generateParenthesis(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[str] 8 | """ 9 | return list(self.createAnswer(n,'',0,0)) 10 | 11 | def createAnswer(self,n,string,left,right): 12 | if left==n and right==n-1: 13 | yield ')' 14 | else: 15 | if left==right or (left>right and left!=n): 16 | for result in self.createAnswer(n,string+'(',left+1,right): 17 | yield '('+result 18 | if left>right: 19 | for result in self.createAnswer(n,string+')',left,right+1): 20 | yield ')'+result -------------------------------------------------------------------------------- /Algorithms/023. Merge k Sorted Lists/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class ListNode(object): 4 | def __init__(self, x): 5 | self.val = x 6 | self.next = None 7 | 8 | class Solution(object): 9 | def mergeKLists(self, lists): 10 | """ 11 | :type lists: List[ListNode] 12 | :rtype: ListNode 13 | """ 14 | l=len(lists) 15 | if l==0: 16 | return None 17 | if l==1: 18 | return lists[0] 19 | left=self.mergeKLists(lists[:l/2]) 20 | right=self.mergeKLists(lists[l/2:]) 21 | ans=ListNode(0) 22 | node=ans 23 | while left or right: 24 | node.next=left if not right or (left and left.val1) { 4 | 5 | int a=0; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (nums[i]>nums[i-1]) { 8 | a=i; 9 | } 10 | } 11 | for (int i = a; i < (a+nums.length)/2; i++) { 12 | int k=nums[i]; 13 | nums[i]=nums[nums.length-i+a-1]; 14 | nums[nums.length-i+a-1]=k; 15 | } 16 | if (a>0) { 17 | for (int i = a; i < nums.length; i++) { 18 | if (nums[a-1]nums[start]: 20 | end=i 21 | arrays=nums[start:end]+nums[end+1:] 22 | arrays.sort() 23 | nums[start]=nums[end] 24 | for i in range(start+1,len(nums)): 25 | nums[i]=arrays[i-start-1] -------------------------------------------------------------------------------- /Algorithms/032. Longest Valid Parentheses/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int longestValidParentheses(String s) { 3 | int length=s.length(); 4 | if (length==0) { 5 | return 0; 6 | } 7 | int ans=0; 8 | char[] c=s.toCharArray(); 9 | int[] vals=new int[length]; 10 | for (int i = length-2; i >= 0; i--) { 11 | if (c[i]=='(') { 12 | int t=i+1+vals[i+1]; 13 | if (t0 else [-1,-1] 12 | def search(self,nums,s,e,target): 13 | if s>e: 14 | return [] 15 | if s==e and nums[s]==target: 16 | return [s] 17 | m=(s+e)/2 18 | if nums[m]target: 21 | return self.search(nums,s,m-1,target) 22 | else: 23 | arrays=self.search(nums,s,m-1,target) 24 | arrays.extend([m]) 25 | arrays.extend(self.search(nums,m+1,e,target)) 26 | return arrays -------------------------------------------------------------------------------- /Algorithms/035. Search Insert Position/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int searchInsert(int[] nums, int target) { 3 | int begin=0; 4 | int end=nums.length-1; 5 | int a=(begin+end)/2; 6 | if (targetnums[nums.length-1]) { 10 | return nums.length; 11 | } 12 | while (nums[a]!=target) { 13 | if (end-1==begin&&(nums[begin]target) { 17 | if (end==a) { 18 | end--; 19 | }else { 20 | end=a; 21 | } 22 | }else { 23 | if (begin==a) { 24 | begin++; 25 | }else { 26 | begin=a; 27 | } 28 | } 29 | a=(begin+end)/2; 30 | } 31 | return a; 32 | } 33 | } -------------------------------------------------------------------------------- /Algorithms/035. Search Insert Position/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def searchInsert(self, nums, target): 5 | """ 6 | :type nums: List[int] 7 | :type target: int 8 | :rtype: int 9 | """ 10 | if targetnums[end]: 14 | return end+1 15 | start=0 16 | while start=state[-1]: 14 | if num==target: 15 | yield [num] 16 | elif num> combinationSum2(int[] candidates, int target) { 3 | Arrays.sort(candidates); 4 | return f(candidates,target,candidates.length-1); 5 | } 6 | public List> f(int[] candidates, int target,int l) { 7 | List> ans=new ArrayList>(); 8 | if (candidates[0]>target||target<0||l<0) { 9 | return ans; 10 | } 11 | for (int i =l; i >=0 ; i--) { 12 | int k=candidates[i]; 13 | if (k==target) { 14 | List list=new ArrayList(); 15 | list.add(k); 16 | ans.add(list); 17 | }else { 18 | List> q=f(candidates,target-k,i-1); 19 | if (q!=null&&q.size()!=0) { 20 | for (int j = 0; j < q.size(); j++) { 21 | List list=q.get(j); 22 | list.add(k); 23 | ans.add(list); 24 | } 25 | } 26 | } 27 | while (i>0&&candidates[i]==candidates[i-1]) { 28 | i--; 29 | } 30 | } 31 | return ans; 32 | } 33 | } -------------------------------------------------------------------------------- /Algorithms/041. First Missing Positive/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int firstMissingPositive(int[] nums) { 3 | for (int i = 0; i < nums.length; i++) { 4 | if (nums[i]!=i+1) { 5 | if (nums[i]<=nums.length&&nums[i]>0&&nums[nums[i]-1]!=nums[i]) { 6 | int k=nums[nums[i]-1]; 7 | nums[nums[i]-1]=nums[i]; 8 | nums[i]=k; 9 | i--; 10 | } 11 | } 12 | } 13 | for (int i = 0; i < nums.length; i++) { 14 | if (nums[i]!=i+1) { 15 | return i+1; 16 | } 17 | } 18 | return nums.length+1; 19 | 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /Algorithms/041. First Missing Positive/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def firstMissingPositive(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | tar=0 10 | nums.append(0) 11 | l=len(nums) 12 | for i in range(l): 13 | b=i 14 | a=nums[i] 15 | while a>0 and amax) { 12 | int s=steps[i]; 13 | for (int j = max+1; j <=n+i; j++) { 14 | if (js+1) { 16 | steps[j]=s+1; 17 | } 18 | } 19 | } 20 | max=n+i; 21 | } 22 | } 23 | return steps[steps.length-1]; 24 | } 25 | } -------------------------------------------------------------------------------- /Algorithms/046. Permutations/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def permute(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[List[int]] 8 | """ 9 | return list(self.create(nums,[])) 10 | def create(self,nums,possibility): 11 | for num in nums: 12 | if num not in possibility: 13 | if len(possibility)==len(nums)-1: 14 | yield [num] 15 | else : 16 | for result in self.create(nums,possibility+[num]): 17 | yield [num]+result 18 | -------------------------------------------------------------------------------- /Algorithms/047. Permutations II/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def permuteUnique(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[List[int]] 8 | """ 9 | return list(self.f(nums,[])) 10 | def f(self,nums,state): 11 | if len(nums)==0: 12 | yield [] 13 | else: 14 | intMap={} 15 | for i in range(len(nums)): 16 | if intMap.get(nums[i]) is None: 17 | #过滤掉重复的组合 18 | intMap[nums[i]]=1 19 | for result in self.f(nums[0:i]+nums[i+1:],state+[nums[i]]): 20 | yield [nums[i]]+result -------------------------------------------------------------------------------- /Algorithms/048. Rotate Image/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n=matrix.length; 4 | for (int i = 0; i < n/2; i++) { 5 | for (int j = i; j > groupAnagrams(String[] strs) { 3 | Arrays.sort(strs); 4 | String[] newStrs=new String[strs.length]; 5 | for (int i = 0; i < strs.length; i++) { 6 | char[] c=strs[i].toCharArray(); 7 | Arrays.sort(c); 8 | newStrs[i]=String.valueOf(c); 9 | } 10 | Map> map=new HashMap>(); 11 | for (int i = 0; i < newStrs.length; i++) { 12 | String str=newStrs[i]; 13 | List list=null; 14 | if (map.get(str)==null) { 15 | list=new ArrayList(); 16 | }else { 17 | list=map.get(str); 18 | } 19 | list.add(i); 20 | map.put(str, list); 21 | } 22 | List> ans=new ArrayList>(); 23 | Set keySet = map.keySet(); 24 | for (String s:keySet) { 25 | List l=map.get(s); 26 | List list=new ArrayList(); 27 | for (int i = 0; i < l.size(); i++) { 28 | list.add(strs[l.get(i)]); 29 | } 30 | ans.add(list); 31 | } 32 | return ans; 33 | } 34 | } -------------------------------------------------------------------------------- /Algorithms/049. Group Anagrams/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def groupAnagrams(self, strs): 5 | """ 6 | :type strs: List[str] 7 | :rtype: List[List[str]] 8 | """ 9 | map={} 10 | strs.sort() 11 | for s in strs: 12 | l=list(s) 13 | l.sort() 14 | eigenValue=str(l) 15 | if map.get(eigenValue) is None: 16 | map[eigenValue]=[s] 17 | else: 18 | map.get(eigenValue).append(s) 19 | return map.values() -------------------------------------------------------------------------------- /Algorithms/050. Pow(x, n)/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public double myPow(double x, int n) { 3 | if (n==0) { 4 | return 1.0; 5 | } 6 | boolean flag=true; 7 | if (n<0) { 8 | n=0-n; 9 | flag=false; 10 | } 11 | boolean slag=true; 12 | if (x<0) { 13 | x=0-x; 14 | if (n%2!=0) { 15 | slag=false; 16 | } 17 | } 18 | if (x==1.0) { 19 | return slag?1.0:-1.0; 20 | } 21 | double answer=1.0; 22 | for (int i = 0; i < n; i++) { 23 | answer*=x; 24 | if (answer==0.0) { 25 | return answer; 26 | } 27 | } 28 | return flag?(slag?answer:-answer):(slag?1/answer:-1/answer); 29 | } 30 | } -------------------------------------------------------------------------------- /Algorithms/050. Pow(x, n)/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def myPow(self, x, n): 5 | """ 6 | :type x: float 7 | :type n: int 8 | :rtype: float 9 | """ 10 | if n<0: 11 | return 1.0/self.myPow(x,-n) 12 | if n==0: 13 | return 1.0 14 | v=self.myPow(x,n/2) 15 | return v*v*(x if n%2==1 else 1) -------------------------------------------------------------------------------- /Algorithms/051. N-Queens/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def solveNQueens(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[List[str]] 8 | """ 9 | ans=[] 10 | for solution in list(self.f(n,())): 11 | a=[] 12 | for pos in solution: 13 | a.append('.'*(pos)+'Q'+'.'*(len(solution)-pos-1)) 14 | ans.append(a) 15 | return ans 16 | def f(self,num,state): 17 | #这里的num表示每行的测试数据 18 | for pos in range(num): 19 | flag=True 20 | #校验,检测到False则停止,if条件写成一行 21 | for i in range(len(state)): 22 | #abs(state[i]-pos)如果等于0表示处于同一列 23 | #abs(state[i]-pos)如果等于len(state)-i表示处于斜线 24 | if abs(state[i]-pos) in (0,len(state)-i):flag=False;break 25 | #如果正确则继续进入生成器 26 | if flag : 27 | #如果当前的state已经只差一个结果,那么直接返回这次测试成功的值 28 | if len(state)==num-1:yield (pos,) 29 | else : 30 | #否则继续测试 31 | for result in self.f(num,state+(pos,)): 32 | yield (pos,)+result -------------------------------------------------------------------------------- /Algorithms/052. N-Queens II/Solution.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeafPages/leetcode/949b080219ae73001a2a91b1bd21c5050a631755/Algorithms/052. N-Queens II/Solution.java -------------------------------------------------------------------------------- /Algorithms/052. N-Queens II/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def totalNQueens(self, n): 5 | """ 6 | :type n: int 7 | :rtype: int 8 | """ 9 | return len(list(self.f(n))) 10 | def f(self,num=8,state=(),): 11 | #这里的num表示每行的测试数据 12 | for pos in range(num): 13 | flag=True 14 | #校验,检测到False则停止,if条件写成一行 15 | for i in range(len(state)): 16 | #abs(state[i]-pos)如果等于0表示处于同一列 17 | #abs(state[i]-pos)如果等于len(state)-i表示处于斜线 18 | if abs(state[i]-pos) in (0,len(state)-i):flag=False;break 19 | #如果正确则继续进入生成器 20 | if flag : 21 | #如果当前的state已经只差一个结果,那么直接返回这次测试成功的值 22 | if len(state)==num-1:yield (pos,) 23 | else : 24 | #否则继续测试 25 | for result in self.f(num,state+(pos,)): 26 | yield (pos,)+result -------------------------------------------------------------------------------- /Algorithms/053. Maximum Subarray/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int sum=0; 4 | int answer=nums[0]; 5 | for (int i = 0; i < nums.length; i++) { 6 | sum+=nums[i]; 7 | if (sum>answer) { 8 | answer=sum; 9 | } 10 | if (sum<0) { 11 | sum=0; 12 | } 13 | } 14 | return answer; 15 | } 16 | } -------------------------------------------------------------------------------- /Algorithms/053. Maximum Subarray/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def maxSubArray(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | ans=nums[0] 10 | sum=0 11 | for num in nums: 12 | sum+=num 13 | if(sum>ans): 14 | ans=sum 15 | if sum<0: 16 | sum=0 17 | return ans -------------------------------------------------------------------------------- /Algorithms/054. Spiral Matrix/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def spiralOrder(self, matrix): 5 | """ 6 | :type matrix: List[List[int]] 7 | :rtype: List[int] 8 | """ 9 | mstep=len(matrix) 10 | if mstep==0: 11 | return [] 12 | nstep=len(matrix[0]) 13 | direction=0 14 | x=0 15 | y=-1 16 | ans=[] 17 | while mstep>0 and nstep>0: 18 | if direction%2==0: 19 | for i in range(1,nstep+1): 20 | y+= 1 if direction%4==0 else -1 21 | ans.append(matrix[x][y]) 22 | mstep-=1 23 | else: 24 | for i in range(1,mstep+1): 25 | x+= 1 if direction%4==1 else -1 26 | ans.append(matrix[x][y]) 27 | nstep-=1 28 | direction+=1 29 | return ans -------------------------------------------------------------------------------- /Algorithms/055. Jump Game/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canJump(int[] nums) { 3 | int k=-1; 4 | int tar=-1; 5 | for (int i = nums.length-1; i>=0 ; i--) { 6 | if (k==-1&&nums[i]==0) { 7 | k=0; 8 | tar=i; 9 | } 10 | if (k==0) { 11 | if(tar==nums.length-1&&nums[i]>=tar-i){ 12 | k=-1; 13 | } 14 | if (nums[i]>tar-i) { 15 | k=-1; 16 | } 17 | } 18 | } 19 | if (k==-1) { 20 | return true; 21 | }else { 22 | return false; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /Algorithms/055. Jump Game/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def canJump(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: bool 8 | """ 9 | nums[-1]=True 10 | index=len(nums)-2 11 | if index<0: 12 | return True 13 | while index>=0: 14 | length=nums[index] 15 | if index+length>=len(nums)-1: 16 | nums[index]=True 17 | else: 18 | flag=False 19 | for i in range(1,length+1): 20 | if nums[index+i]: 21 | flag=True 22 | break 23 | nums[index]=flag 24 | index-=1 25 | return nums[0] -------------------------------------------------------------------------------- /Algorithms/057. Insert Interval/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for an interval. 4 | class Interval(object): 5 | def __init__(self, s=0, e=0): 6 | self.start = s 7 | self.end = e 8 | 9 | class Solution(object): 10 | def insert(self, intervals, newInterval): 11 | """ 12 | :type intervals: List[Interval] 13 | :type newInterval: Interval 14 | :rtype: List[Interval] 15 | """ 16 | if len(intervals)==0: 17 | return [newInterval] 18 | ns=newInterval.start 19 | ne=newInterval.end 20 | start=-1 21 | end=-1 22 | for i in range(len(intervals)): 23 | if start==-1: 24 | e=intervals[i].end 25 | if e>=ns: 26 | start=i 27 | s=intervals[i].start 28 | if s<=ne: 29 | end=i 30 | else: 31 | break 32 | if start==-1: 33 | return intervals+[newInterval] 34 | if end==-1: 35 | return [newInterval]+intervals 36 | ansStart=intervals[start].start if intervals[start].startnewInterval.end else newInterval.end 38 | intervals[start:end+1]=[Interval(ansStart,ansEnd)] 39 | return intervals -------------------------------------------------------------------------------- /Algorithms/058. Length of Last Word/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLastWord(String s) { 3 | if (s.length()==0) { 4 | return 0; 5 | } 6 | int e=-1; 7 | for (int i = s.length()-1; i >=0; i--) { 8 | if (!s.substring(i,i+1).equals(" ")) { 9 | e=i; 10 | break; 11 | } 12 | } 13 | if (e==-1) { 14 | return 0; 15 | } 16 | int b=-1; 17 | for (int i = e-1; i >=0; i--) { 18 | if (s.substring(i,i+1).equals(" ")) { 19 | b=i; 20 | break; 21 | } 22 | } 23 | System.out.println("b="+b); 24 | return b==-1?e+1:e-b; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/058. Length of Last Word/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def lengthOfLastWord(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | strs=s.split(' ') 10 | for i in range(len(strs)-1,-1,-1): 11 | if len(strs[i])!=0 : return len(strs[i]) 12 | return 0 -------------------------------------------------------------------------------- /Algorithms/059. Spiral Matrix II/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] generateMatrix(int n) { 3 | int[][] answer = new int[n][n]; 4 | // 顶部 5 | int t = 0; 6 | // 底部 7 | int b = n - 1; 8 | // 左边 9 | int l = 0; 10 | // 右边 11 | int r = n - 1; 12 | int a = 1; 13 | while (true) { 14 | // 左 15 | for (int i = l; i <= r; i++) { 16 | answer[t][i] = a; 17 | a++; 18 | } 19 | t++; 20 | if (t > b) { 21 | return answer; 22 | } 23 | // 下 24 | for (int i = t; i <= b; i++) { 25 | answer[i][r] = a; 26 | a++; 27 | } 28 | r--; 29 | if (l > r) { 30 | return answer; 31 | } 32 | // 右 33 | for (int i = r; i >= l; i--) { 34 | answer[b][i] = a; 35 | a++; 36 | } 37 | b--; 38 | if (t > b) { 39 | return answer; 40 | } 41 | // 上 42 | for (int i = b; i >= t; i--) { 43 | answer[i][l] = a; 44 | a++; 45 | } 46 | l++; 47 | if (l > r) { 48 | return answer; 49 | } 50 | 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Algorithms/059. Spiral Matrix II/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def generateMatrix(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[List[int]] 8 | """ 9 | ans= [[0 for col in range(n)] for row in range(n)] 10 | step=n 11 | direction=x=a=0 12 | y=-1 13 | while step>0: 14 | for i in range(1,step+1): 15 | a+=1 16 | if direction%2==0: 17 | y+= 1 if direction%4==0 else -1 18 | else: 19 | x+= 1 if direction%4==1 else -1 20 | ans[x][y]=a 21 | if direction%2==0: 22 | step-=1 23 | direction+=1 24 | return ans -------------------------------------------------------------------------------- /Algorithms/060. Permutation Sequence/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String getPermutation(int n, int k) { 3 | int s=1; 4 | List list=new ArrayList(); 5 | for (int i = 0; i 0: 17 | pro/=len(nums) 18 | i=k/(pro) 19 | ans+=str(nums[i]) 20 | nums[i:i+1]=[] 21 | k-=i*pro 22 | return ans -------------------------------------------------------------------------------- /Algorithms/061. Rotate List/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode rotateRight(ListNode head, int k) { 11 | if (head==null) { 12 | return head; 13 | } 14 | ListNode l=head; 15 | List list=new ArrayList(); 16 | while (l!=null) { 17 | list.add(l); 18 | l=l.next; 19 | } 20 | k=k%list.size(); 21 | if (k==0) { 22 | return head; 23 | } 24 | list.get(list.size()-k-1).next=null; 25 | list.get(list.size()-1).next=head; 26 | return list.get(list.size()-k); 27 | } 28 | } -------------------------------------------------------------------------------- /Algorithms/061. Rotate List/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | # class ListNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def rotateRight(self, head, k): 11 | """ 12 | :type head: ListNode 13 | :type k: int 14 | :rtype: ListNode 15 | """ 16 | length=self.getLength(head) 17 | if not head or length==0 or k%length==0: 18 | return head 19 | else: 20 | k=k%length 21 | node=head 22 | while length-k>1: 23 | node=node.next 24 | length-=1 25 | end=self.getEndNode(head) 26 | end.next=head 27 | ans=node.next 28 | node.next=None 29 | return ans 30 | def getLength(self,head): 31 | ans=0 32 | while head: 33 | ans+=1 34 | head=head.next 35 | return ans 36 | def getEndNode(self,head): 37 | while head.next: 38 | head=head.next 39 | return head -------------------------------------------------------------------------------- /Algorithms/062. Unique Paths/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePaths(int m, int n) { 3 | if (m==1||n==1) { 4 | return 1; 5 | } 6 | Map map=new HashMap(); 7 | for (int i = 0; i < m; i++) { 8 | map.put(i, 1); 9 | } 10 | for (int i = 1; i < n-1; i++) { 11 | int sum=0; 12 | for (int j = m-1; j >=0; j--) { 13 | sum+=map.get(j); 14 | } 15 | int k=map.get(m-1); 16 | for (int j = m-1; j >=0; j--) { 17 | map.put(j, sum); 18 | sum-=k; 19 | if (j>1) { 20 | k=map.get(j-1); 21 | } 22 | } 23 | } 24 | int sum=0; 25 | for (int i = 0; i < m; i++) { 26 | sum+=map.get(i); 27 | } 28 | return sum; 29 | } 30 | } -------------------------------------------------------------------------------- /Algorithms/062. Unique Paths/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def uniquePaths(self, m, n): 5 | """ 6 | :type m: int 7 | :type n: int 8 | :rtype: int 9 | """ 10 | matrix= [([0] * n) for i in range(m)] 11 | for i in range(m): 12 | for j in range(n): 13 | if i==0 or j==0: 14 | matrix[i][j]=1 15 | else: 16 | matrix[i][j]=matrix[i-1][j]+matrix[i][j-1] 17 | return matrix[m-1][n-1] -------------------------------------------------------------------------------- /Algorithms/063. Unique Paths II/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 | if (obstacleGrid[0][0]==1||obstacleGrid[obstacleGrid.length-1][obstacleGrid[0].length-1]==1) { 4 | return 0; 5 | } 6 | Map map=new HashMap(); 7 | return f(obstacleGrid,0,0,obstacleGrid.length-1,obstacleGrid[0].length-1,map); 8 | } 9 | public int f(int[][] obstacleGrid,int x,int y,int xl,int yl,Map map){ 10 | String coordinate=x+","+y; 11 | if (x==xl&&y==yl) { 12 | return 1; 13 | } 14 | if (map.get(coordinate)==null) { 15 | boolean xflag=(x=0); 15 | if (flag) { 16 | int[] answer=new int[digits.length+1]; 17 | answer[0]=1; 18 | return answer; 19 | }else { 20 | return digits; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /Algorithms/067. Add Binary/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def addBinary(self, a, b): 5 | """ 6 | :type a: str 7 | :type b: str 8 | :rtype: str 9 | """ 10 | flag=False 11 | la=len(a) 12 | lb=len(b) 13 | l=max(la,lb) 14 | ans='' 15 | for i in range(1,l+1): 16 | t=(0 if i>la else int(a[-i])) + (0 if i>lb else int(b[-i])) + (1 if flag else 0) 17 | ans=str(t%2)+ans 18 | flag=t/2==1 19 | return ('1' if flag else '') +ans -------------------------------------------------------------------------------- /Algorithms/068. Text Justification/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def fullJustify(self, words, maxWidth): 5 | """ 6 | :type words: List[str] 7 | :type maxWidth: int 8 | :rtype: List[str] 9 | """ 10 | ansList=[] 11 | a=[] 12 | l=maxWidth 13 | for word in words: 14 | if len(word)<=l: 15 | a.append(word) 16 | l-=(len(word)+1) 17 | else: 18 | l+=len(a) 19 | if len(a)==1: 20 | text=a[0]+' '*l 21 | ansList.append(text) 22 | else: 23 | eachSpaceLength=l/(len(a)-1) 24 | extra=l%(len(a)-1) 25 | text=a[0] 26 | for i in range(1,len(a)): 27 | text+=(' '*(eachSpaceLength+(1 if i<=extra else 0))+a[i]) 28 | ansList.append(text) 29 | l=maxWidth-len(word)-1 30 | a=[word] 31 | if len(a)!=0: 32 | text='' 33 | for word in a: 34 | text+=(word+' ') 35 | text=text[:-1]+' '*(l+1) 36 | ansList.append(text) 37 | return ansList -------------------------------------------------------------------------------- /Algorithms/069. Sqrt(x)/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int mySqrt(int x) { 3 | if(x==0){ 4 | return 0; 5 | } 6 | if(x==1){ 7 | return 1; 8 | } 9 | int s=1; 10 | for (int i = 0; i <20; i++) { 11 | s=(x/s)/2+s/2; 12 | } 13 | int k=0; 14 | int answer=0; 15 | for (int i = -30; i < 30; i++) { 16 | k=s+i; 17 | if (k*k>0&&k*k<=x) { 18 | answer=k; 19 | } 20 | } 21 | return answer; 22 | } 23 | } -------------------------------------------------------------------------------- /Algorithms/069. Sqrt(x)/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | import math 4 | class Solution(object): 5 | def mySqrt(self, x): 6 | """ 7 | :type x: int 8 | :rtype: int 9 | """ 10 | return int(math.sqrt(x)) -------------------------------------------------------------------------------- /Algorithms/070. Climbing Stairs/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int climbStairs(int n) { 3 | if (n<=2) { 4 | return n; 5 | }else { 6 | int[] sk=new int[n]; 7 | sk[0]=1; 8 | sk[1]=2; 9 | for (int i =2; i < sk.length; i++) { 10 | sk[i]=sk[i-1]+sk[i-2]; 11 | } 12 | return sk[n-1]; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /Algorithms/070. Climbing Stairs/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def climbStairs(self, n): 5 | """ 6 | :type n: int 7 | :rtype: int 8 | """ 9 | if n<3: 10 | return n 11 | ans=[] 12 | ans.append(1) 13 | ans.append(2) 14 | for i in range(2,n): 15 | ans.append(ans[-1]+ans[-2]) 16 | return ans[-1] -------------------------------------------------------------------------------- /Algorithms/072. Edit Distance/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minDistance(String word1, String word2) { 3 | int l1=word1.length(); 4 | int l2=word2.length(); 5 | if (l1*l2==0) { 6 | return l1==0?l2:l1; 7 | } 8 | int[][] board=new int[l1+1][l2+1]; 9 | for (int i = 0; i < l1+1; i++) { 10 | board[i][0]=i; 11 | } 12 | for (int i = 0; i < l2+1; i++) { 13 | board[0][i]=i; 14 | } 15 | char[] c1=word1.toCharArray(); 16 | char[] c2=word2.toCharArray(); 17 | for (int i = 1; i < l1+1; i++) { 18 | for (int j = 1; j < l2+1; j++) { 19 | if (c1[i-1]==c2[j-1]) { 20 | board[i][j]=board[i-1][j-1]; 21 | }else { 22 | board[i][j]=Math.min(Math.min(board[i-1][j], board[i][j-1]), board[i-1][j-1])+1; 23 | } 24 | } 25 | } 26 | return board[l1][l2]; 27 | } 28 | } -------------------------------------------------------------------------------- /Algorithms/072. Edit Distance/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def minDistance(self, word1, word2): 5 | """ 6 | :type word1: str 7 | :type word2: str 8 | :rtype: int 9 | """ 10 | l1=len(word1) 11 | l2=len(word2) 12 | dict=[[0 for col in range(l1+1)] for row in range(l2+1)] 13 | for x in range(l2+1): 14 | for y in range(l1+1): 15 | if x*y==0: 16 | dict[x][y]=max(x,y) 17 | else: 18 | dict[x][y]=dict[x-1][y-1] if word1[y-1]==word2[x-1] else (1+min(dict[x-1][y],dict[x][y-1],dict[x-1][y-1])) 19 | return dict[-1][-1] -------------------------------------------------------------------------------- /Algorithms/073. Set Matrix Zeroes/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | boolean f=true; 4 | for (int i = 0; i < matrix.length; i++) { 5 | if (matrix[i][0]==0) { 6 | f=false; 7 | break; 8 | } 9 | } 10 | boolean l=true; 11 | for (int i = 0; i < matrix[0].length; i++) { 12 | if (matrix[0][i]==0) { 13 | l=false; 14 | } 15 | } 16 | for (int i = 0; i < matrix.length; i++) { 17 | for (int j = 0; j < matrix[i].length; j++) { 18 | if (matrix[i][j]==0) { 19 | matrix[i][0]=0; 20 | matrix[0][j]=0; 21 | } 22 | } 23 | } 24 | for (int i = 1; i < matrix.length; i++) { 25 | for (int j = 1; j < matrix[i].length; j++) { 26 | if (matrix[i][0]==0||matrix[0][j]==0) { 27 | matrix[i][j]=0; 28 | } 29 | } 30 | } 31 | if (!f) { 32 | for (int i = 0; i < matrix.length; i++) { 33 | matrix[i][0]=0; 34 | } 35 | } 36 | if (!l) { 37 | for (int i = 0; i < matrix[0].length; i++) { 38 | matrix[0][i]=0; 39 | } 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Algorithms/073. Set Matrix Zeroes/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def setZeroes(self, matrix): 5 | """ 6 | :type matrix: List[List[int]] 7 | :rtype: void Do not return anything, modify matrix in-place instead. 8 | """ 9 | #列 10 | n=[1 for col in range(len(matrix[0]))] 11 | #行 12 | m=[1 for row in range(len(matrix))] 13 | for i in range(len(matrix)): 14 | for j in range(len(matrix[i])): 15 | if matrix[i][j]==0: 16 | n[j]=0 17 | m[i]=0 18 | for i in range(len(matrix)): 19 | for j in range(len(matrix[i])): 20 | if m[i]==0 or n[j]==0: 21 | matrix[i][j]=0 -------------------------------------------------------------------------------- /Algorithms/074. Search a 2D Matrix/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def searchMatrix(self, matrix, target): 5 | """ 6 | :type matrix: List[List[int]] 7 | :type target: int 8 | :rtype: bool 9 | """ 10 | row=len(matrix) 11 | if row==0: 12 | return False 13 | col=len(matrix[0]) 14 | begin=0 15 | end=row*col 16 | while begintarget: 24 | end=middle 25 | else: 26 | begin=middle+1 27 | return False -------------------------------------------------------------------------------- /Algorithms/075. Sort Colors/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void sortColors(int[] nums) { 3 | int t=0; 4 | int b=0; 5 | int e=nums.length-1; 6 | boolean flag=true; 7 | for (int i = 0; i < nums.length; i++) { 8 | if (flag) { 9 | if (nums[b]!=0) { 10 | t=b; 11 | flag=false; 12 | }else { 13 | t++; 14 | } 15 | b++; 16 | }else { 17 | if (nums[e]==0) { 18 | nums[e]=nums[t]; 19 | nums[t]=0; 20 | flag=true; 21 | t++; 22 | } 23 | e--; 24 | } 25 | } 26 | b=t; 27 | e=nums.length-1; 28 | flag=true; 29 | for (int i = t; i < nums.length; i++) { 30 | if (flag) { 31 | if (nums[b]!=1) { 32 | t=b; 33 | flag=false; 34 | } 35 | b++; 36 | }else { 37 | if (nums[e]==1) { 38 | nums[e]=nums[t]; 39 | nums[t]=1; 40 | flag=true; 41 | } 42 | e--; 43 | } 44 | } 45 | 46 | 47 | } 48 | } -------------------------------------------------------------------------------- /Algorithms/075. Sort Colors/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def sortColors(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: void Do not return anything, modify nums in-place instead. 8 | """ 9 | low=0 10 | mid=0 11 | high=len(nums)-1 12 | while mid<=high: 13 | if nums[mid]==2: 14 | nums[mid]=nums[high] 15 | nums[high]=2 16 | high-=1 17 | elif nums[mid]==1: 18 | mid+=1 19 | else: 20 | nums[low]=0 21 | if mid!=low: 22 | nums[mid]=1 23 | low+=1 24 | mid+=1 25 | print nums -------------------------------------------------------------------------------- /Algorithms/077. Combinations/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def combine(self, n, k): 5 | """ 6 | :type n: int 7 | :type k: int 8 | :rtype: List[List[int]] 9 | """ 10 | nums=range(n+1) 11 | nums.remove(0) 12 | return list(self.f(nums,k,[])) 13 | def f(self,nums,k,state): 14 | for num in nums: 15 | if len(state)==0 or num>state[-1]: 16 | if len(state)==k-1: 17 | yield [num] 18 | else: 19 | for result in self.f(nums,k,state+[num]): 20 | yield [num]+result -------------------------------------------------------------------------------- /Algorithms/078. Subsets/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> subsets(int[] nums) { 3 | for (int i = 0; i < nums.length; i++) { 4 | for (int j = i+1; j < nums.length; j++) { 5 | if (nums[i]>nums[j]) { 6 | int temp=nums[i]; 7 | nums[i]=nums[j]; 8 | nums[j]=temp; 9 | } 10 | } 11 | } 12 | int[] n=new int[nums.length]; 13 | int sum=1; 14 | for (int i = 0; i < n.length; i++) { 15 | n[i]=sum; 16 | sum*=2; 17 | } 18 | List> answer=new ArrayList>(); 19 | for (int i = 0; i < sum; i++) { 20 | List list=new ArrayList(); 21 | for (int j = 0; j < nums.length; j++) { 22 | if ((i/n[j])%2==1) { 23 | list.add(nums[j]); 24 | } 25 | } 26 | answer.add(list); 27 | } 28 | return answer; 29 | } 30 | } -------------------------------------------------------------------------------- /Algorithms/078. Subsets/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def subsets(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[List[int]] 8 | """ 9 | return [[]]+list(self.f(nums,[])) 10 | 11 | def f(self,nums,state): 12 | """ 13 | :type nums: List[int] 14 | :type state: List[int] 15 | :rtype: List[int] 16 | """ 17 | for num in nums: 18 | if len(state)==0 or num>state[-1]: 19 | yield [num] 20 | for result in self.f(nums,state+[num]): 21 | yield [num]+result -------------------------------------------------------------------------------- /Algorithms/080. Remove Duplicates from Sorted Array II/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums.length<3) { 4 | return nums.length; 5 | } 6 | boolean flag=true; 7 | int k=0; 8 | int t=nums[0]; 9 | for (int i = 1; i < nums.length; i++) { 10 | t=nums[i-1]; 11 | nums[i-k]=nums[i]; 12 | if (nums[i]==t) { 13 | if (flag) { 14 | flag=false; 15 | }else { 16 | k++; 17 | } 18 | }else { 19 | flag=true; 20 | } 21 | } 22 | return nums.length-k; 23 | } 24 | } -------------------------------------------------------------------------------- /Algorithms/080. Remove Duplicates from Sorted Array II/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def removeDuplicates(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | if len(nums)<3: 10 | return len(nums) 11 | sign=nums[0] 12 | flag=False 13 | i=1 14 | while i map=new HashMap(); 3 | public boolean isScramble(String s1, String s2) { 4 | if (map.get(s1+","+s2)!=null) { 5 | return map.get(s1+","+s2); 6 | } 7 | int length=s1.length(); 8 | if (length!=s2.length()) { 9 | map.put(s1+","+s2, false); 10 | return false; 11 | } 12 | boolean flag=false; 13 | if (length==1) { 14 | flag=s1.equals(s2); 15 | map.put(s1+","+s2, flag); 16 | return flag; 17 | } 18 | for (int i = 1; i =0; i--) { 4 | nums1[i+nums1.length-m]=nums1[i]; 5 | } 6 | int a=nums1.length-m; 7 | int b=0; 8 | for (int i = 0; i < m+n; i++) { 9 | if (a==nums1.length) { 10 | nums1[i]=nums2[b]; 11 | b++; 12 | }else if (b==n||nums1[a]nums2[sn]: 20 | nums1[sm+1:m+1]=nums1[sm:m] 21 | nums1[sm]=nums2[sn] 22 | m+=1 23 | sn+=1 24 | sm+=1 -------------------------------------------------------------------------------- /Algorithms/089. Gray Code/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List grayCode(int n) { 3 | List ans=new ArrayList(); 4 | List list=new ArrayList(); 5 | if (n==0) { 6 | ans.add(0); 7 | return ans; 8 | } 9 | list.add("0"); 10 | list.add("1"); 11 | for (int i = 1; i < n; i++) { 12 | List newList=new ArrayList(); 13 | for (int j = 0; j < list.size(); j++) { 14 | newList.add("0"+list.get(j)); 15 | } 16 | for (int j = list.size()-1; j >= 0 ; j--) { 17 | newList.add("1"+list.get(j)); 18 | } 19 | list=newList; 20 | } 21 | for (int i = 0; i < list.size(); i++) { 22 | ans.add(Integer.valueOf(list.get(i), 2)); 23 | } 24 | return ans; 25 | } 26 | } -------------------------------------------------------------------------------- /Algorithms/089. Gray Code/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def grayCode(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[int] 8 | """ 9 | if n==0: 10 | return [0] 11 | else: 12 | ans=self.grayCode(n-1) 13 | return ans+[pow(2,n-1)+x for x in ans[::-1]] -------------------------------------------------------------------------------- /Algorithms/090. Subsets II/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def subsetsWithDup(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[List[int]] 8 | """ 9 | nums.sort() 10 | index=list(self.f(nums,[])) 11 | ans=[[]] 12 | for ind in index: 13 | a=[] 14 | for i in ind: 15 | a.append(nums[i]) 16 | if a not in ans: 17 | ans.append(a) 18 | return ans 19 | 20 | def f(self,nums,state): 21 | """ 22 | :type nums: List[int] 23 | :type state: List[int] 24 | :rtype: List[int] 25 | """ 26 | for i in range(len(nums)): 27 | if len(state)==0 or i>state[-1]: 28 | yield [i] 29 | for result in self.f(nums,state+[i]): 30 | yield [i]+result -------------------------------------------------------------------------------- /Algorithms/091. Decode Ways/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numDecodings(String s) { 3 | if (s.length()==0) { 4 | return 0; 5 | } 6 | Map map=new HashMap(); 7 | return f(s,map); 8 | } 9 | public int f(String s,Map map){ 10 | if (s.length()==0) { 11 | return 1; 12 | } 13 | if (map.get(s)==null) { 14 | int length=s.length(); 15 | int one=-1; 16 | if (length>=1) { 17 | one=Integer.parseInt(s.substring(0,1)); 18 | } 19 | int two=-1; 20 | if (length>=2) { 21 | two=Integer.parseInt(s.substring(0,2)); 22 | } 23 | int value=(one>0?f(s.substring(1,s.length()),map):0)+((one>0&&two>0&&two<27)?f(s.substring(2,s.length()),map):0); 24 | map.put(s, value); 25 | return value; 26 | } 27 | return map.get(s); 28 | } 29 | } -------------------------------------------------------------------------------- /Algorithms/091. Decode Ways/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def numDecodings(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | l=len(s) 10 | if l==0: 11 | return 0 12 | if l==1: 13 | return 0 if s=='0' else 1 14 | ans=[0]*l 15 | ans[-1]=(1 if int(s[-1])!=0 else 0) 16 | ans[-2]=0 if int(s[-2])==0 else (1 if int(s[-2:])<27 else 0)+ans[-1] 17 | i=l-3 18 | while i>=0: 19 | ans[i]=0 if int(s[i])==0 else (ans[i+1]+(ans[i+2] if int(s[i:i+2])<27 else 0)) 20 | i-=1 21 | return ans[0] 22 | -------------------------------------------------------------------------------- /Algorithms/092. Reverse Linked List II/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode reverseBetween(ListNode head, int m, int n) { 11 | List list=f(head, new ArrayList()); 12 | list.get(m-1).next=list.get(n-1).next; 13 | for (int i = n-1; i >=m; i--) { 14 | list.get(i).next=list.get(i-1); 15 | } 16 | if (m!=1) { 17 | list.get(m-2).next=list.get(n-1); 18 | return list.get(0); 19 | }else { 20 | return list.get(n-1); 21 | } 22 | } 23 | public List f(ListNode head,List list){ 24 | if (head!=null) { 25 | list.add(head); 26 | list=f(head.next,list); 27 | } 28 | return list; 29 | } 30 | } -------------------------------------------------------------------------------- /Algorithms/093. Restore IP Addresses/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def restoreIpAddresses(self, s): 5 | """ 6 | :type s: str 7 | :rtype: List[str] 8 | """ 9 | return list(self.f(s,'',0)) 10 | def f(self,s,state,num): 11 | if num==4: 12 | if len(s)==0: 13 | yield '' 14 | if num<4: 15 | if len(s)>0: 16 | if s[0]=='0': 17 | for result in self.f(s[1:],state+'.0',num+1): 18 | yield '0'+('.'+result if len(result)!=0 else '') 19 | else: 20 | for j in range(1,min(3,len(s))+1): 21 | i=int(s[:j]) 22 | if i>=0 and i<256: 23 | for result in self.f(s[j:],state+'.'+str(i),num+1): 24 | yield str(i)+('.'+result if len(result)!=0 else '') -------------------------------------------------------------------------------- /Algorithms/094. Binary Tree Inorder Traversal/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List inorderTraversal(TreeNode root) { 12 | return inorder(root,new ArrayList()); 13 | } 14 | public List inorder(TreeNode root,List list){ 15 | if (root!=null) { 16 | list=inorder(root.left,list); 17 | list.add(root.val); 18 | list=inorder(root.right,list); 19 | } 20 | return list; 21 | } 22 | } -------------------------------------------------------------------------------- /Algorithms/094. Binary Tree Inorder Traversal/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for a binary tree node. 4 | # class TreeNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | class Solution(object): 11 | def inorderTraversal(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: List[int] 15 | """ 16 | if root is None: 17 | return [] 18 | ans=[] 19 | ans.extend(self.inorderTraversal(root.left)) 20 | ans.append(root.val) 21 | ans.extend(self.inorderTraversal(root.right)) 22 | return ans -------------------------------------------------------------------------------- /Algorithms/096. Unique Binary Search Trees/Solution.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numTrees(int n) { 3 | return f(n,new HashMap()); 4 | } 5 | public int f(int n,Map map){ 6 | if (map.get(n)!=null) { 7 | return map.get(n); 8 | }else { 9 | 10 | if (n==1||n==0) { 11 | return 1; 12 | }else { 13 | int sum=0; 14 | for (int i = 0; i < n; i++) { 15 | int left=f(i,map); 16 | int right=f((n-1-i),map); 17 | sum+=(left*right); 18 | } 19 | map.put(n,sum); 20 | return sum; 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Algorithms/096. Unique Binary Search Trees/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def __init__(self): 5 | self.map={} 6 | def numTrees(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | if n<=1 : 12 | return 1 13 | if n not in self.map: 14 | ans=0 15 | for i in range(0,n): 16 | ans+=(self.numTrees(i)*self.numTrees(n-1-i)) 17 | self.map[n]=ans 18 | else : 19 | ans=self.map[n] 20 | return ans -------------------------------------------------------------------------------- /Algorithms/097. Interleaving String/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def isInterleave(self, s1, s2, s3): 5 | """ 6 | :type s1: str 7 | :type s2: str 8 | :type s3: str 9 | :rtype: bool 10 | """ 11 | l1=len(s1) 12 | l2=len(s2) 13 | if l1+l2!=len(s3): 14 | return False 15 | matrix=[[False for col in range(l1+1)] for row in range(l2+1)] 16 | matrix[l2][l1]=True 17 | for i in range(1,l1+1): 18 | ans=s1[-i]==s3[-i] 19 | if ans: 20 | matrix[l2][l1-i]=True 21 | else: 22 | break 23 | for i in range(1,l2+1): 24 | ans=s2[-i]==s3[-i] 25 | if ans: 26 | matrix[l2-i][l1]=True 27 | else: 28 | break 29 | for i in range(l2-1,-1,-1): 30 | for j in range(l1-1,-1,-1): 31 | matrix[i][j]=(s2[i]==s3[i+j] and matrix[i+1][j]) or (s1[j]==s3[i+j] and matrix[i][j+1]) 32 | return matrix[0][0] -------------------------------------------------------------------------------- /Algorithms/098. Validate Binary Search Tree/Solution.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isValidBST(TreeNode root) { 12 | if (root==null) { 13 | return true; 14 | } 15 | List list=inorder(root,new ArrayList()); 16 | if (list.size()<2) { 17 | return true; 18 | } 19 | for (int i = 0; i < list.size()-1; i++) { 20 | if (list.get(i)>=list.get(i+1)) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | public List inorder(TreeNode root,List list){ 27 | if (root!=null) { 28 | list=inorder(root.left,list); 29 | list.add(root.val); 30 | list=inorder(root.right,list); 31 | } 32 | return list; 33 | } 34 | } -------------------------------------------------------------------------------- /Algorithms/098. Validate Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for a binary tree node. 4 | # class TreeNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | class Solution(object): 11 | def isValidBST(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: bool 15 | """ 16 | if root is None: 17 | return True 18 | leftVal=self.maxNodeVal(root.left) 19 | rightVal=self.minNodeVal(root.right) 20 | return False if (leftVal and leftVal>=root.val) or (rightVal and rightVal<=root.val) else self.isValidBST(root.left) and self.isValidBST(root.right) 21 | def maxNodeVal(self,root): 22 | if root is None: 23 | return None 24 | midVal=root.val 25 | leftVal=self.maxNodeVal(root.left) 26 | rightVal=self.maxNodeVal(root.right) 27 | return max(leftVal if leftVal else midVal,rightVal if rightVal else midVal,midVal) 28 | def minNodeVal(self,root): 29 | if root is None: 30 | return None 31 | midVal=root.val 32 | leftVal=self.minNodeVal(root.left) 33 | rightVal=self.minNodeVal(root.right) 34 | return min(leftVal if leftVal else midVal,rightVal if rightVal else midVal,midVal) -------------------------------------------------------------------------------- /Algorithms/099. Recover Binary Search Tree/Solution.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for a binary tree node. 4 | class TreeNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.left = None 8 | self.right = None 9 | class Solution(object): 10 | _pre=_m1=_m2=None 11 | def recoverTree(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: void Do not return anything, modify root in-place instead. 15 | """ 16 | self._pre=self._m1=self._m2=None 17 | self.findMistakes(root) 18 | val=self._m1.val 19 | self._m1.val=self._m2.val 20 | self._m2.val=val 21 | def findMistakes(self,root): 22 | if not root: 23 | return 24 | if root.left: 25 | self.findMistakes(root.left) 26 | if self._pre and root.val map=new HashMap(); 5 | List list=new LinkedList(); 6 | for (int i = 0; i < s.length(); i++) { 7 | String k=s.substring(i, i+1); 8 | if (map.get(k) != null) { 9 | int n=map.get(k)-map.get(list.get(0))+1; 10 | for (int j = 0; j < n; j++) { 11 | map.remove(list.get(0)); 12 | list.remove(0); 13 | } 14 | } 15 | map.put(k, i); 16 | list.add(k); 17 | if (list.size()>answer) { 18 | answer=list.size(); 19 | } 20 | } 21 | return answer; 22 | } 23 | } -------------------------------------------------------------------------------- /java/006. ZigZag Conversion.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String convert(String s, int numRows) { 3 | if(numRows==1){ 4 | return s; 5 | }else{ 6 | int k=numRows*2-2; 7 | String[] res=new String[numRows]; 8 | for (int i = 0; i < res.length; i++) { 9 | res[i]=""; 10 | } 11 | int step=0; 12 | int j=0; 13 | for (int i = 0; i < s.length(); i++) { 14 | step++; 15 | if (step<=numRows) { 16 | j=step; 17 | }else { 18 | j=numRows-(step-numRows); 19 | } 20 | res[j-1]+=s.substring(i, i+1); 21 | if (step==k) { 22 | step=0; 23 | } 24 | } 25 | String result=""; 26 | for (int i = 0; i < res.length; i++) { 27 | result+=res[i]; 28 | } 29 | return result; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /java/007. Reverse Integer.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int reverse(int x) { 3 | String str=String.valueOf(x); 4 | String r=""; 5 | int re=0; 6 | if (x<0) { 7 | for (int i = str.length()-1; i >0 ; i--) { 8 | r+=str.substring(i,i+1); 9 | } 10 | r="-"+r; 11 | }else { 12 | for (int i = str.length()-1; i >-1 ; i--) { 13 | r+=str.substring(i,i+1); 14 | } 15 | } 16 | try { 17 | re=Integer.parseInt(r); 18 | 19 | } catch (Exception e) { 20 | 21 | } 22 | return re; 23 | } 24 | } -------------------------------------------------------------------------------- /java/008. String to Integer (atoi).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int myAtoi(String str) { 3 | char[] cs=str.toCharArray(); 4 | long ans=0; 5 | int sign=1; 6 | boolean signFlag=true; 7 | int i=0; 8 | boolean zeroFlag=true; 9 | while (i < cs.length) { 10 | if (zeroFlag) { 11 | while (cs[i]==' ') { 12 | i++; 13 | } 14 | zeroFlag=false; 15 | } 16 | if (!zeroFlag&&cs[i]==' ') { 17 | break; 18 | } 19 | if (cs[i]=='-'||cs[i]=='+') { 20 | if (signFlag) { 21 | sign=44-cs[i]; 22 | signFlag=false; 23 | }else{ 24 | return 0; 25 | } 26 | }else if(cs[i]>='0'&&cs[i]<='9'){ 27 | ans=10*ans+cs[i]-48; 28 | if (sign==1&&ans>=Integer.MAX_VALUE) { 29 | return Integer.MAX_VALUE; 30 | } 31 | if (sign==-1&&ans-1>=Integer.MAX_VALUE) { 32 | return Integer.MIN_VALUE; 33 | } 34 | }else{ 35 | break; 36 | } 37 | i++; 38 | } 39 | return (int) (ans*sign); 40 | } 41 | } -------------------------------------------------------------------------------- /java/009. Palindrome Number.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isPalindrome(int x) { 3 | if (x < 0) { 4 | return false; 5 | } 6 | int n = x; 7 | int a = 0; 8 | int p = 1; 9 | while (x != 0) { 10 | x /= 10; 11 | a++; 12 | p *= 10; 13 | if (a==1) { 14 | p/=10; 15 | } 16 | } 17 | int b = a / 2; 18 | if (b == 0) { 19 | return true; 20 | } 21 | 22 | for (int i = 0; i < b; i++) { 23 | int begin = n / p; 24 | int end = n % 10; 25 | if (begin != end) { 26 | return false; 27 | } else { 28 | n = n - (begin * p); 29 | p /= 100; 30 | n = (n - end) / 10; 31 | } 32 | } 33 | return true; 34 | } 35 | } -------------------------------------------------------------------------------- /java/011. Container With Most Water.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxArea(int[] height) { 3 | int left=0; 4 | int right=height.length-1; 5 | int ans=(right-left)*Math.min(height[left], height[right]); 6 | while (right>left) { 7 | int water=(right-left)*Math.min(height[left], height[right]); 8 | if (water>ans) { 9 | ans=water; 10 | } 11 | if (height[left]> ans=new ArrayList>(); 3 | public List> threeSum(int[] nums) { 4 | Arrays.sort(nums); 5 | if (nums.length<3) { 6 | return ans; 7 | } 8 | int length=nums.length; 9 | for (int i = 0; i < length-2; i++) { 10 | if (i==0||nums[i]!=nums[i-1]) { 11 | f(nums,nums[i],i+1,length-1); 12 | } 13 | } 14 | return ans; 15 | } 16 | public void f(int[] nums,int target,int s,int e){ 17 | while (s list=new ArrayList(); 21 | list.add(target); 22 | list.add(nums[s]); 23 | list.add(nums[e]); 24 | ans.add(list); 25 | while (s list=new ArrayList(); 12 | list=addlist(head, list); 13 | if (list.size()==n) { 14 | return head.next; 15 | } 16 | list.get(list.size()-n-1).next=n==1?null:list.get(list.size()-n+1); 17 | return head; 18 | } 19 | public List addlist(ListNode head, List list){ 20 | if (head!=null) { 21 | list.add(head); 22 | }else { 23 | return list; 24 | } 25 | return addlist(head.next, list); 26 | } 27 | } -------------------------------------------------------------------------------- /java/021. Merge Two Sorted Lists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 | if (l1==null) { 12 | return l2; 13 | } 14 | if (l2==null) { 15 | return l1; 16 | } 17 | ListNode l=null; 18 | if (l1.val>l2.val) { 19 | l=new ListNode(l2.val); 20 | l.next=mergeTwoLists(l1,l2.next); 21 | }else { 22 | l=new ListNode(l1.val); 23 | l.next=mergeTwoLists(l1.next,l2); 24 | } 25 | return l; 26 | } 27 | } -------------------------------------------------------------------------------- /java/024. Swap Nodes in Pairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode swapPairs(ListNode head) { 11 | if (head==null||head.next==null) { 12 | return head; 13 | }else { 14 | int val=head.val; 15 | head.val=head.next.val; 16 | head.next.val=val; 17 | head.next.next=swapPairs(head.next.next); 18 | } 19 | return head; 20 | } 21 | } -------------------------------------------------------------------------------- /java/026. Remove Duplicates from Sorted Array.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if(nums.length<=1){ 4 | return nums.length; 5 | } 6 | int tar=nums[0]; 7 | int l=1; 8 | int end=nums.length; 9 | int kuang=0; 10 | for (int i = 1; i < end; i++) { 11 | if (nums[i]==tar) { 12 | for (int j = i; j < end-1; j++) { 13 | kuang=nums[j]; 14 | nums[j]=nums[j+1]; 15 | nums[j+1]=kuang; 16 | } 17 | end--; 18 | i--; 19 | }else { 20 | tar=nums[i]; 21 | l++; 22 | } 23 | } 24 | return l; 25 | } 26 | } -------------------------------------------------------------------------------- /java/027. Remove Element.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeElement(int[] nums, int val) { 3 | int end=nums.length; 4 | int k=0; 5 | for (int i = 0; i < end; i++) { 6 | if (nums[i]==val) { 7 | for (int j = i; j < end-1; j++) { 8 | k=nums[j]; 9 | nums[j]=nums[j+1]; 10 | nums[j+1]=k; 11 | } 12 | end--; 13 | i--; 14 | } 15 | } 16 | return end; 17 | } 18 | } -------------------------------------------------------------------------------- /java/028. Implement strStr().java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int strStr(String haystack, String needle) { 3 | if (needle.length()==0) { 4 | return 0; 5 | } 6 | for (int i = 0; i 1) { 4 | 5 | int a=0; 6 | for (int i = 1; i < nums.length; i++) { 7 | if (nums[i]>nums[i-1]) { 8 | a=i; 9 | } 10 | } 11 | for (int i = a; i < (a+nums.length)/2; i++) { 12 | int k=nums[i]; 13 | nums[i]=nums[nums.length-i+a-1]; 14 | nums[nums.length-i+a-1]=k; 15 | } 16 | if (a>0) { 17 | for (int i = a; i < nums.length; i++) { 18 | if (nums[a-1]= 0; i--) { 11 | if (c[i]=='(') { 12 | int t=i+1+vals[i+1]; 13 | if (tnums[nums.length-1]) { 10 | return nums.length; 11 | } 12 | while (nums[a]!=target) { 13 | if (end-1==begin&&(nums[begin]target) { 17 | if (end==a) { 18 | end--; 19 | }else { 20 | end=a; 21 | } 22 | }else { 23 | if (begin==a) { 24 | begin++; 25 | }else { 26 | begin=a; 27 | } 28 | } 29 | a=(begin+end)/2; 30 | } 31 | return a; 32 | } 33 | } -------------------------------------------------------------------------------- /java/038. Count and Say.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String countAndSay(int n) { 3 | if (n == 1) { 4 | return "1"; 5 | } 6 | String answer = "1"; 7 | for (int i = 0; i < n - 1; i++) { 8 | answer = new Solution().readNum(answer); 9 | } 10 | return answer; 11 | } 12 | 13 | public String readNum(String num) { 14 | int n = 1; 15 | String t = num.substring(0, 1); 16 | StringBuffer answer=new StringBuffer(); 17 | String k = ""; 18 | for (int i = 1; i < num.length(); i++) { 19 | k = num.substring(i, i + 1); 20 | if (k.equals(t)) { 21 | n++; 22 | } else { 23 | answer=answer.append(n).append(t); 24 | t = k; 25 | n = 1; 26 | } 27 | } 28 | answer = answer.append(n).append(t); 29 | return answer.toString(); 30 | } 31 | } -------------------------------------------------------------------------------- /java/040. Combination Sum II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> combinationSum2(int[] candidates, int target) { 3 | Arrays.sort(candidates); 4 | return f(candidates,target,candidates.length-1); 5 | } 6 | public List> f(int[] candidates, int target,int l) { 7 | List> ans=new ArrayList>(); 8 | if (candidates[0]>target||target<0||l<0) { 9 | return ans; 10 | } 11 | for (int i =l; i >=0 ; i--) { 12 | int k=candidates[i]; 13 | if (k==target) { 14 | List list=new ArrayList(); 15 | list.add(k); 16 | ans.add(list); 17 | }else { 18 | List> q=f(candidates,target-k,i-1); 19 | if (q!=null&&q.size()!=0) { 20 | for (int j = 0; j < q.size(); j++) { 21 | List list=q.get(j); 22 | list.add(k); 23 | ans.add(list); 24 | } 25 | } 26 | } 27 | while (i>0&&candidates[i]==candidates[i-1]) { 28 | i--; 29 | } 30 | } 31 | return ans; 32 | } 33 | } -------------------------------------------------------------------------------- /java/041. First Missing Positive.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int firstMissingPositive(int[] nums) { 3 | for (int i = 0; i < nums.length; i++) { 4 | if (nums[i]!=i+1) { 5 | if (nums[i]<=nums.length&&nums[i]>0&&nums[nums[i]-1]!=nums[i]) { 6 | int k=nums[nums[i]-1]; 7 | nums[nums[i]-1]=nums[i]; 8 | nums[i]=k; 9 | i--; 10 | } 11 | } 12 | } 13 | for (int i = 0; i < nums.length; i++) { 14 | if (nums[i]!=i+1) { 15 | return i+1; 16 | } 17 | } 18 | return nums.length+1; 19 | 20 | 21 | } 22 | } -------------------------------------------------------------------------------- /java/045. Jump Game II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int jump(int[] nums) { 3 | if (nums.length==1) { 4 | return 0; 5 | } 6 | int max=0; 7 | int[] steps=new int[nums.length]; 8 | steps[0]=0; 9 | for (int i = 0; i < nums.length-1; i++) { 10 | int n=nums[i]; 11 | if (n+i>max) { 12 | int s=steps[i]; 13 | for (int j = max+1; j <=n+i; j++) { 14 | if (js+1) { 16 | steps[j]=s+1; 17 | } 18 | } 19 | } 20 | max=n+i; 21 | } 22 | } 23 | return steps[steps.length-1]; 24 | } 25 | } -------------------------------------------------------------------------------- /java/048. Rotate Image.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n=matrix.length; 4 | for (int i = 0; i < n/2; i++) { 5 | for (int j = i; j > groupAnagrams(String[] strs) { 3 | Arrays.sort(strs); 4 | String[] newStrs=new String[strs.length]; 5 | for (int i = 0; i < strs.length; i++) { 6 | char[] c=strs[i].toCharArray(); 7 | Arrays.sort(c); 8 | newStrs[i]=String.valueOf(c); 9 | } 10 | Map> map=new HashMap>(); 11 | for (int i = 0; i < newStrs.length; i++) { 12 | String str=newStrs[i]; 13 | List list=null; 14 | if (map.get(str)==null) { 15 | list=new ArrayList(); 16 | }else { 17 | list=map.get(str); 18 | } 19 | list.add(i); 20 | map.put(str, list); 21 | } 22 | List> ans=new ArrayList>(); 23 | Set keySet = map.keySet(); 24 | for (String s:keySet) { 25 | List l=map.get(s); 26 | List list=new ArrayList(); 27 | for (int i = 0; i < l.size(); i++) { 28 | list.add(strs[l.get(i)]); 29 | } 30 | ans.add(list); 31 | } 32 | return ans; 33 | } 34 | } -------------------------------------------------------------------------------- /java/050. Pow(x, n).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public double myPow(double x, int n) { 3 | if (n==0) { 4 | return 1.0; 5 | } 6 | boolean flag=true; 7 | if (n<0) { 8 | n=0-n; 9 | flag=false; 10 | } 11 | boolean slag=true; 12 | if (x<0) { 13 | x=0-x; 14 | if (n%2!=0) { 15 | slag=false; 16 | } 17 | } 18 | if (x==1.0) { 19 | return slag?1.0:-1.0; 20 | } 21 | double answer=1.0; 22 | for (int i = 0; i < n; i++) { 23 | answer*=x; 24 | if (answer==0.0) { 25 | return answer; 26 | } 27 | } 28 | return flag?(slag?answer:-answer):(slag?1/answer:-1/answer); 29 | } 30 | } -------------------------------------------------------------------------------- /java/052. N-Queens II.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeafPages/leetcode/949b080219ae73001a2a91b1bd21c5050a631755/java/052. N-Queens II.java -------------------------------------------------------------------------------- /java/053. Maximum Subarray.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int maxSubArray(int[] nums) { 3 | int sum=0; 4 | int answer=nums[0]; 5 | for (int i = 0; i < nums.length; i++) { 6 | sum+=nums[i]; 7 | if (sum>answer) { 8 | answer=sum; 9 | } 10 | if (sum<0) { 11 | sum=0; 12 | } 13 | } 14 | return answer; 15 | } 16 | } -------------------------------------------------------------------------------- /java/055. Jump Game.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean canJump(int[] nums) { 3 | int k=-1; 4 | int tar=-1; 5 | for (int i = nums.length-1; i>=0 ; i--) { 6 | if (k==-1&&nums[i]==0) { 7 | k=0; 8 | tar=i; 9 | } 10 | if (k==0) { 11 | if(tar==nums.length-1&&nums[i]>=tar-i){ 12 | k=-1; 13 | } 14 | if (nums[i]>tar-i) { 15 | k=-1; 16 | } 17 | } 18 | } 19 | if (k==-1) { 20 | return true; 21 | }else { 22 | return false; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /java/058. Length of Last Word.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int lengthOfLastWord(String s) { 3 | if (s.length()==0) { 4 | return 0; 5 | } 6 | int e=-1; 7 | for (int i = s.length()-1; i >=0; i--) { 8 | if (!s.substring(i,i+1).equals(" ")) { 9 | e=i; 10 | break; 11 | } 12 | } 13 | if (e==-1) { 14 | return 0; 15 | } 16 | int b=-1; 17 | for (int i = e-1; i >=0; i--) { 18 | if (s.substring(i,i+1).equals(" ")) { 19 | b=i; 20 | break; 21 | } 22 | } 23 | System.out.println("b="+b); 24 | return b==-1?e+1:e-b; 25 | } 26 | } -------------------------------------------------------------------------------- /java/059. Spiral Matrix II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[][] generateMatrix(int n) { 3 | int[][] answer = new int[n][n]; 4 | // 顶部 5 | int t = 0; 6 | // 底部 7 | int b = n - 1; 8 | // 左边 9 | int l = 0; 10 | // 右边 11 | int r = n - 1; 12 | int a = 1; 13 | while (true) { 14 | // 左 15 | for (int i = l; i <= r; i++) { 16 | answer[t][i] = a; 17 | a++; 18 | } 19 | t++; 20 | if (t > b) { 21 | return answer; 22 | } 23 | // 下 24 | for (int i = t; i <= b; i++) { 25 | answer[i][r] = a; 26 | a++; 27 | } 28 | r--; 29 | if (l > r) { 30 | return answer; 31 | } 32 | // 右 33 | for (int i = r; i >= l; i--) { 34 | answer[b][i] = a; 35 | a++; 36 | } 37 | b--; 38 | if (t > b) { 39 | return answer; 40 | } 41 | // 上 42 | for (int i = b; i >= t; i--) { 43 | answer[i][l] = a; 44 | a++; 45 | } 46 | l++; 47 | if (l > r) { 48 | return answer; 49 | } 50 | 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /java/060. Permutation Sequence.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public String getPermutation(int n, int k) { 3 | int s=1; 4 | List list=new ArrayList(); 5 | for (int i = 0; i list=new ArrayList(); 16 | while (l!=null) { 17 | list.add(l); 18 | l=l.next; 19 | } 20 | k=k%list.size(); 21 | if (k==0) { 22 | return head; 23 | } 24 | list.get(list.size()-k-1).next=null; 25 | list.get(list.size()-1).next=head; 26 | return list.get(list.size()-k); 27 | } 28 | } -------------------------------------------------------------------------------- /java/062. Unique Paths.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePaths(int m, int n) { 3 | if (m==1||n==1) { 4 | return 1; 5 | } 6 | Map map=new HashMap(); 7 | for (int i = 0; i < m; i++) { 8 | map.put(i, 1); 9 | } 10 | for (int i = 1; i < n-1; i++) { 11 | int sum=0; 12 | for (int j = m-1; j >=0; j--) { 13 | sum+=map.get(j); 14 | } 15 | int k=map.get(m-1); 16 | for (int j = m-1; j >=0; j--) { 17 | map.put(j, sum); 18 | sum-=k; 19 | if (j>1) { 20 | k=map.get(j-1); 21 | } 22 | } 23 | } 24 | int sum=0; 25 | for (int i = 0; i < m; i++) { 26 | sum+=map.get(i); 27 | } 28 | return sum; 29 | } 30 | } -------------------------------------------------------------------------------- /java/063. Unique Paths II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 | if (obstacleGrid[0][0]==1||obstacleGrid[obstacleGrid.length-1][obstacleGrid[0].length-1]==1) { 4 | return 0; 5 | } 6 | Map map=new HashMap(); 7 | return f(obstacleGrid,0,0,obstacleGrid.length-1,obstacleGrid[0].length-1,map); 8 | } 9 | public int f(int[][] obstacleGrid,int x,int y,int xl,int yl,Map map){ 10 | String coordinate=x+","+y; 11 | if (x==xl&&y==yl) { 12 | return 1; 13 | } 14 | if (map.get(coordinate)==null) { 15 | boolean xflag=(x map=new HashMap(); 6 | return f(grid,0,0,xl,yl,map); 7 | } 8 | public int f(int[][] grid,int x,int y,int xl,int yl,Map map){ 9 | String coordinate=x+","+y; 10 | if (map.get(coordinate)==null) { 11 | if (x>=xl||y>=yl) { 12 | return -1; 13 | }else { 14 | int xv=f(grid,x+1,y,xl,yl,map); 15 | int yv=f(grid,x,y+1,xl,yl,map); 16 | int v=0; 17 | if (xv<0) { 18 | v=yv; 19 | }else if (yv<0) { 20 | v=xv; 21 | }else if (xv>yv){ 22 | v=yv; 23 | }else { 24 | v=xv; 25 | } 26 | int value=grid[x][y]+(v<0?0:v); 27 | map.put(coordinate, value); 28 | return value; 29 | } 30 | } 31 | return map.get(coordinate); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/066. Plus One.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int[] plusOne(int[] digits) { 3 | int i=digits.length-1; 4 | boolean flag= false; 5 | do { 6 | if (digits[i]<9) { 7 | digits[i]+=1; 8 | flag=false; 9 | }else { 10 | digits[i]=0; 11 | flag=true; 12 | } 13 | i--; 14 | } while (flag&&i>=0); 15 | if (flag) { 16 | int[] answer=new int[digits.length+1]; 17 | answer[0]=1; 18 | return answer; 19 | }else { 20 | return digits; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /java/069. Sqrt(x).java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int mySqrt(int x) { 3 | if(x==0){ 4 | return 0; 5 | } 6 | if(x==1){ 7 | return 1; 8 | } 9 | int s=1; 10 | for (int i = 0; i <20; i++) { 11 | s=(x/s)/2+s/2; 12 | } 13 | int k=0; 14 | int answer=0; 15 | for (int i = -30; i < 30; i++) { 16 | k=s+i; 17 | if (k*k>0&&k*k<=x) { 18 | answer=k; 19 | } 20 | } 21 | return answer; 22 | } 23 | } -------------------------------------------------------------------------------- /java/070. Climbing Stairs.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int climbStairs(int n) { 3 | if (n<=2) { 4 | return n; 5 | }else { 6 | int[] sk=new int[n]; 7 | sk[0]=1; 8 | sk[1]=2; 9 | for (int i =2; i < sk.length; i++) { 10 | sk[i]=sk[i-1]+sk[i-2]; 11 | } 12 | return sk[n-1]; 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /java/072. Edit Distance.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int minDistance(String word1, String word2) { 3 | int l1=word1.length(); 4 | int l2=word2.length(); 5 | if (l1*l2==0) { 6 | return l1==0?l2:l1; 7 | } 8 | int[][] board=new int[l1+1][l2+1]; 9 | for (int i = 0; i < l1+1; i++) { 10 | board[i][0]=i; 11 | } 12 | for (int i = 0; i < l2+1; i++) { 13 | board[0][i]=i; 14 | } 15 | char[] c1=word1.toCharArray(); 16 | char[] c2=word2.toCharArray(); 17 | for (int i = 1; i < l1+1; i++) { 18 | for (int j = 1; j < l2+1; j++) { 19 | if (c1[i-1]==c2[j-1]) { 20 | board[i][j]=board[i-1][j-1]; 21 | }else { 22 | board[i][j]=Math.min(Math.min(board[i-1][j], board[i][j-1]), board[i-1][j-1])+1; 23 | } 24 | } 25 | } 26 | return board[l1][l2]; 27 | } 28 | } -------------------------------------------------------------------------------- /java/073. Set Matrix Zeroes.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void setZeroes(int[][] matrix) { 3 | boolean f=true; 4 | for (int i = 0; i < matrix.length; i++) { 5 | if (matrix[i][0]==0) { 6 | f=false; 7 | break; 8 | } 9 | } 10 | boolean l=true; 11 | for (int i = 0; i < matrix[0].length; i++) { 12 | if (matrix[0][i]==0) { 13 | l=false; 14 | } 15 | } 16 | for (int i = 0; i < matrix.length; i++) { 17 | for (int j = 0; j < matrix[i].length; j++) { 18 | if (matrix[i][j]==0) { 19 | matrix[i][0]=0; 20 | matrix[0][j]=0; 21 | } 22 | } 23 | } 24 | for (int i = 1; i < matrix.length; i++) { 25 | for (int j = 1; j < matrix[i].length; j++) { 26 | if (matrix[i][0]==0||matrix[0][j]==0) { 27 | matrix[i][j]=0; 28 | } 29 | } 30 | } 31 | if (!f) { 32 | for (int i = 0; i < matrix.length; i++) { 33 | matrix[i][0]=0; 34 | } 35 | } 36 | if (!l) { 37 | for (int i = 0; i < matrix[0].length; i++) { 38 | matrix[0][i]=0; 39 | } 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /java/075. Sort Colors.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public void sortColors(int[] nums) { 3 | int t=0; 4 | int b=0; 5 | int e=nums.length-1; 6 | boolean flag=true; 7 | for (int i = 0; i < nums.length; i++) { 8 | if (flag) { 9 | if (nums[b]!=0) { 10 | t=b; 11 | flag=false; 12 | }else { 13 | t++; 14 | } 15 | b++; 16 | }else { 17 | if (nums[e]==0) { 18 | nums[e]=nums[t]; 19 | nums[t]=0; 20 | flag=true; 21 | t++; 22 | } 23 | e--; 24 | } 25 | } 26 | b=t; 27 | e=nums.length-1; 28 | flag=true; 29 | for (int i = t; i < nums.length; i++) { 30 | if (flag) { 31 | if (nums[b]!=1) { 32 | t=b; 33 | flag=false; 34 | } 35 | b++; 36 | }else { 37 | if (nums[e]==1) { 38 | nums[e]=nums[t]; 39 | nums[t]=1; 40 | flag=true; 41 | } 42 | e--; 43 | } 44 | } 45 | 46 | 47 | } 48 | } -------------------------------------------------------------------------------- /java/078. Subsets.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> subsets(int[] nums) { 3 | for (int i = 0; i < nums.length; i++) { 4 | for (int j = i+1; j < nums.length; j++) { 5 | if (nums[i]>nums[j]) { 6 | int temp=nums[i]; 7 | nums[i]=nums[j]; 8 | nums[j]=temp; 9 | } 10 | } 11 | } 12 | int[] n=new int[nums.length]; 13 | int sum=1; 14 | for (int i = 0; i < n.length; i++) { 15 | n[i]=sum; 16 | sum*=2; 17 | } 18 | List> answer=new ArrayList>(); 19 | for (int i = 0; i < sum; i++) { 20 | List list=new ArrayList(); 21 | for (int j = 0; j < nums.length; j++) { 22 | if ((i/n[j])%2==1) { 23 | list.add(nums[j]); 24 | } 25 | } 26 | answer.add(list); 27 | } 28 | return answer; 29 | } 30 | } -------------------------------------------------------------------------------- /java/080. Remove Duplicates from Sorted Array II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int removeDuplicates(int[] nums) { 3 | if (nums.length<3) { 4 | return nums.length; 5 | } 6 | boolean flag=true; 7 | int k=0; 8 | int t=nums[0]; 9 | for (int i = 1; i < nums.length; i++) { 10 | t=nums[i-1]; 11 | nums[i-k]=nums[i]; 12 | if (nums[i]==t) { 13 | if (flag) { 14 | flag=false; 15 | }else { 16 | k++; 17 | } 18 | }else { 19 | flag=true; 20 | } 21 | } 22 | return nums.length-k; 23 | } 24 | } -------------------------------------------------------------------------------- /java/081. Search in Rotated Sorted Array II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean search(int[] nums, int target) { 3 | for (int i = 0; i < nums.length; i++) { 4 | if (nums[i]==target) { 5 | return true; 6 | } 7 | } 8 | return false; 9 | } 10 | } -------------------------------------------------------------------------------- /java/082. Remove Duplicates from Sorted List II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode deleteDuplicates(ListNode head) { 11 | head=findFirst(head); 12 | if (head!=null) { 13 | head.next=deleteDuplicates(head.next); 14 | } 15 | return head; 16 | } 17 | public ListNode findFirst(ListNode head) { 18 | if (head==null||head.next==null||head.val!=head.next.val) { 19 | return head; 20 | } 21 | int i=head.val; 22 | while (head!=null) { 23 | if (head.val!=i) { 24 | return findFirst(head); 25 | } 26 | head=head.next; 27 | } 28 | return null; 29 | } 30 | } -------------------------------------------------------------------------------- /java/083. Remove Duplicates from Sorted List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode deleteDuplicates(ListNode head) { 11 | if (head==null||head.next==null) { 12 | return head; 13 | } 14 | if (head.val==head.next.val) { 15 | head.next=head.next.next; 16 | head=deleteDuplicates(head); 17 | }else { 18 | head.next=deleteDuplicates(head.next); 19 | } 20 | return head; 21 | } 22 | } -------------------------------------------------------------------------------- /java/087. Scramble String.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | Map map=new HashMap(); 3 | public boolean isScramble(String s1, String s2) { 4 | if (map.get(s1+","+s2)!=null) { 5 | return map.get(s1+","+s2); 6 | } 7 | int length=s1.length(); 8 | if (length!=s2.length()) { 9 | map.put(s1+","+s2, false); 10 | return false; 11 | } 12 | boolean flag=false; 13 | if (length==1) { 14 | flag=s1.equals(s2); 15 | map.put(s1+","+s2, flag); 16 | return flag; 17 | } 18 | for (int i = 1; i =0; i--) { 4 | nums1[i+nums1.length-m]=nums1[i]; 5 | } 6 | int a=nums1.length-m; 7 | int b=0; 8 | for (int i = 0; i < m+n; i++) { 9 | if (a==nums1.length) { 10 | nums1[i]=nums2[b]; 11 | b++; 12 | }else if (b==n||nums1[a] grayCode(int n) { 3 | List ans=new ArrayList(); 4 | List list=new ArrayList(); 5 | if (n==0) { 6 | ans.add(0); 7 | return ans; 8 | } 9 | list.add("0"); 10 | list.add("1"); 11 | for (int i = 1; i < n; i++) { 12 | List newList=new ArrayList(); 13 | for (int j = 0; j < list.size(); j++) { 14 | newList.add("0"+list.get(j)); 15 | } 16 | for (int j = list.size()-1; j >= 0 ; j--) { 17 | newList.add("1"+list.get(j)); 18 | } 19 | list=newList; 20 | } 21 | for (int i = 0; i < list.size(); i++) { 22 | ans.add(Integer.valueOf(list.get(i), 2)); 23 | } 24 | return ans; 25 | } 26 | } -------------------------------------------------------------------------------- /java/090. Subsets II.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public List> subsetsWithDup(int[] nums) { 3 | for (int i = 0; i < nums.length; i++) { 4 | for (int j = i+1; j < nums.length; j++) { 5 | if (nums[i]=0;i--) { 15 | n[i]=sum; 16 | sum*=2; 17 | } 18 | List> answer=new ArrayList>(); 19 | for (int i = 0; i < sum; i++) { 20 | List list=new ArrayList(); 21 | for (int j = nums.length-1; j >=0 ; j--) { 22 | if ((i/n[j])%2==1) { 23 | list.add(nums[j]); 24 | } 25 | } 26 | answer.add(list); 27 | } 28 | Map, Integer> map=new HashMap, Integer>(); 29 | for (int i = 0; i < answer.size(); i++) { 30 | if (map.get(answer.get(i))==null) { 31 | map.put(answer.get(i), 1); 32 | }else { 33 | answer.remove(i); 34 | i--; 35 | } 36 | } 37 | return answer; 38 | } 39 | } -------------------------------------------------------------------------------- /java/091. Decode Ways.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numDecodings(String s) { 3 | if (s.length()==0) { 4 | return 0; 5 | } 6 | Map map=new HashMap(); 7 | return f(s,map); 8 | } 9 | public int f(String s,Map map){ 10 | if (s.length()==0) { 11 | return 1; 12 | } 13 | if (map.get(s)==null) { 14 | int length=s.length(); 15 | int one=-1; 16 | if (length>=1) { 17 | one=Integer.parseInt(s.substring(0,1)); 18 | } 19 | int two=-1; 20 | if (length>=2) { 21 | two=Integer.parseInt(s.substring(0,2)); 22 | } 23 | int value=(one>0?f(s.substring(1,s.length()),map):0)+((one>0&&two>0&&two<27)?f(s.substring(2,s.length()),map):0); 24 | map.put(s, value); 25 | return value; 26 | } 27 | return map.get(s); 28 | } 29 | } -------------------------------------------------------------------------------- /java/092. Reverse Linked List II.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | public class Solution { 10 | public ListNode reverseBetween(ListNode head, int m, int n) { 11 | List list=f(head, new ArrayList()); 12 | list.get(m-1).next=list.get(n-1).next; 13 | for (int i = n-1; i >=m; i--) { 14 | list.get(i).next=list.get(i-1); 15 | } 16 | if (m!=1) { 17 | list.get(m-2).next=list.get(n-1); 18 | return list.get(0); 19 | }else { 20 | return list.get(n-1); 21 | } 22 | } 23 | public List f(ListNode head,List list){ 24 | if (head!=null) { 25 | list.add(head); 26 | list=f(head.next,list); 27 | } 28 | return list; 29 | } 30 | } -------------------------------------------------------------------------------- /java/094. Binary Tree Inorder Traversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public List inorderTraversal(TreeNode root) { 12 | return inorder(root,new ArrayList()); 13 | } 14 | public List inorder(TreeNode root,List list){ 15 | if (root!=null) { 16 | list=inorder(root.left,list); 17 | list.add(root.val); 18 | list=inorder(root.right,list); 19 | } 20 | return list; 21 | } 22 | } -------------------------------------------------------------------------------- /java/096. Unique Binary Search Trees.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public int numTrees(int n) { 3 | return f(n,new HashMap()); 4 | } 5 | public int f(int n,Map map){ 6 | if (map.get(n)!=null) { 7 | return map.get(n); 8 | }else { 9 | 10 | if (n==1||n==0) { 11 | return 1; 12 | }else { 13 | int sum=0; 14 | for (int i = 0; i < n; i++) { 15 | int left=f(i,map); 16 | int right=f((n-1-i),map); 17 | sum+=(left*right); 18 | } 19 | map.put(n,sum); 20 | return sum; 21 | } 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /java/098. Validate Binary Search Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isValidBST(TreeNode root) { 12 | if (root==null) { 13 | return true; 14 | } 15 | List list=inorder(root,new ArrayList()); 16 | if (list.size()<2) { 17 | return true; 18 | } 19 | for (int i = 0; i < list.size()-1; i++) { 20 | if (list.get(i)>=list.get(i+1)) { 21 | return false; 22 | } 23 | } 24 | return true; 25 | } 26 | public List inorder(TreeNode root,List list){ 27 | if (root!=null) { 28 | list=inorder(root.left,list); 29 | list.add(root.val); 30 | list=inorder(root.right,list); 31 | } 32 | return list; 33 | } 34 | } -------------------------------------------------------------------------------- /java/100. Same Tree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | public class Solution { 11 | public boolean isSameTree(TreeNode p, TreeNode q) { 12 | if (p==null&&q==null) { 13 | return true; 14 | }else if (p==null||q==null) { 15 | return false; 16 | } 17 | if (p.val!=q.val) { 18 | return false; 19 | }else{ 20 | return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right); 21 | } 22 | 23 | } 24 | } -------------------------------------------------------------------------------- /python/001. Two Sum.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def twoSum(self, nums, target): 5 | map={} 6 | for i in range(nums.__len__()): 7 | map[(target-nums[i])]=i 8 | for i in range(nums.__len__()): 9 | if(map.get(nums[i])): 10 | ans=[] 11 | ans.append(i+1) 12 | ans.append(map.get(nums[i])+1) 13 | return ans 14 | -------------------------------------------------------------------------------- /python/002. Add Two Numbers.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | class ListNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.next = None 8 | 9 | class Solution(object): 10 | def addTwoNumbers(self, l1, l2): 11 | return Solution().addTwo(l1,l2,False) 12 | def addTwo(self,l1,l2,flag): 13 | t=False 14 | val=0; 15 | if(l1): 16 | val+=l1.val 17 | t=True 18 | if(l2): 19 | val+=l2.val 20 | t=True 21 | if(flag): 22 | val+=1 23 | t=True 24 | if(val>=10): 25 | flag=True 26 | val-=10 27 | else : 28 | flag=False 29 | if(t): 30 | ans=ListNode(val) 31 | ans.next=Solution().addTwo(l1.next if l1 else None ,l2.next if l2 else None,flag) 32 | return ans 33 | else : 34 | return None 35 | 36 | 37 | a=ListNode(0) 38 | b=ListNode(0) 39 | sol=Solution() 40 | print sol.addTwoNumbers(a,b) -------------------------------------------------------------------------------- /python/003. Longest Substring Without Repeating Characters.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def lengthOfLongestSubstring(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | if(s.__len__()==0): 10 | return 0 11 | map={} 12 | max=0 13 | begin=0 14 | for i in range(s.__len__()): 15 | if(map.get(s[i])!=None): 16 | if(i-begin>max): 17 | max=i-begin 18 | if(map.get(s[i])+1>begin): 19 | begin=map.get(s[i])+1 20 | map[s[i]]=i 21 | print begin 22 | if(s.__len__()-begin>max): 23 | max=s.__len__()-begin 24 | return max 25 | s="abcb" 26 | print Solution().lengthOfLongestSubstring(s) -------------------------------------------------------------------------------- /python/006. ZigZag Conversion.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def convert(self, s, numRows): 5 | """ 6 | :type s: str 7 | :type numRows: int 8 | :rtype: str 9 | """ 10 | if(s.__len__()==0): 11 | return '' 12 | if(numRows==1): 13 | return s 14 | n=2*numRows-2 15 | ans=[] 16 | for i in range(numRows): 17 | a=[] 18 | ans.append(a) 19 | for i in range(s.__len__()): 20 | k=i%n 21 | if(k2147483647 or ans<-2147483648): 23 | return 0 24 | return ans 25 | 26 | 27 | x=1000 28 | print str(x).strip('0')[::-1] if x>0 else '-'+str(-x).strip('0')[::-1] 29 | -------------------------------------------------------------------------------- /python/009. Palindrome Number.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def isPalindrome(self, x): 5 | """ 6 | :type x: int 7 | :rtype: bool 8 | """ 9 | return str(x)==str(x)[::-1] -------------------------------------------------------------------------------- /python/012. Integer to Roman.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | _numsToRoman=[ 5 | ['','I','II','III','IV','V','VI','VII','VIII','IX','X'], 6 | ['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C'], 7 | ['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM','M'], 8 | ['','M','MM','MMM'], 9 | ] 10 | def intToRoman(self, num): 11 | """ 12 | :type num: int 13 | :rtype: str 14 | """ 15 | s='0'*(4-len(str(num)))+str(num) 16 | ntr=self._numsToRoman 17 | return ntr[3][int(s[0])]+ntr[2][int(s[1])]+ntr[1][int(s[2])]+ntr[0][int(s[3])] -------------------------------------------------------------------------------- /python/014. Longest Common Prefix.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def longestCommonPrefix(self, strs): 5 | """ 6 | :type strs: List[str] 7 | :rtype: str 8 | """ 9 | if len(strs)==0: 10 | return '' 11 | ans=strs[0] 12 | for str in strs: 13 | ans=self.findSameWord(str,ans) 14 | return ans 15 | 16 | def findSameWord(self,str1,str2): 17 | if len(str1)>len(str2): 18 | return self.findSameWord(str2,str1) 19 | l=len(str1) 20 | if l==0: 21 | return '' 22 | ans='' 23 | for i in range(l): 24 | if str1[i]==str2[i]: 25 | ans+=str1[i] 26 | else: 27 | break 28 | return ans -------------------------------------------------------------------------------- /python/017. Letter Combinations of a Phone Number.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | keyboard={} 5 | keyboard['2']=list('abc') 6 | keyboard['3']=list('def') 7 | keyboard['4']=list('ghi') 8 | keyboard['5']=list('jkl') 9 | keyboard['6']=list('mno') 10 | keyboard['7']=list('pqrs') 11 | keyboard['8']=list('tuv') 12 | keyboard['9']=list('wxyz') 13 | def letterCombinations(self, digits): 14 | """ 15 | :type digits: str 16 | :rtype: List[str] 17 | """ 18 | return list(self.f(digits,'')) if len(digits)>0 else [] 19 | def f(self,string,state): 20 | for v in self.keyboard.get(string[0]): 21 | if len(string)==1: 22 | yield v 23 | else: 24 | for result in self.f(string[1:],state+v): 25 | yield v+result -------------------------------------------------------------------------------- /python/019. Remove Nth Node From End of List.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | # class ListNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def removeNthFromEnd(self, head, n): 11 | """ 12 | :type head: ListNode 13 | :type n: int 14 | :rtype: ListNode 15 | """ 16 | array=[] 17 | while head: 18 | array.append(head) 19 | head=head.next 20 | if n==1: 21 | if len(array)==1: 22 | return None 23 | else: 24 | array[-2].next=None 25 | else: 26 | array[-n].val=array[-n].next.val 27 | array[-n].next=array[-n].next.next 28 | return array[0] -------------------------------------------------------------------------------- /python/021. Merge Two Sorted Lists.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | # class ListNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def mergeTwoLists(self, l1, l2): 11 | """ 12 | :type l1: ListNode 13 | :type l2: ListNode 14 | :rtype: ListNode 15 | """ 16 | if l1 is None: 17 | return l2 18 | if l2 is None: 19 | return l1 20 | ans=None 21 | if l1.val<=l2.val: 22 | ans=l1 23 | ans.next=self.mergeTwoLists(l1.next,l2) 24 | else: 25 | ans=l2 26 | ans.next=self.mergeTwoLists(l1,l2.next) 27 | return ans -------------------------------------------------------------------------------- /python/022. Generate Parentheses.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def generateParenthesis(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[str] 8 | """ 9 | return list(self.createAnswer(n,'',0,0)) 10 | 11 | def createAnswer(self,n,string,left,right): 12 | if left==n and right==n-1: 13 | yield ')' 14 | else: 15 | if left==right or (left>right and left!=n): 16 | for result in self.createAnswer(n,string+'(',left+1,right): 17 | yield '('+result 18 | if left>right: 19 | for result in self.createAnswer(n,string+')',left,right+1): 20 | yield ')'+result -------------------------------------------------------------------------------- /python/023. Merge k Sorted Lists.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class ListNode(object): 4 | def __init__(self, x): 5 | self.val = x 6 | self.next = None 7 | 8 | class Solution(object): 9 | def mergeKLists(self, lists): 10 | """ 11 | :type lists: List[ListNode] 12 | :rtype: ListNode 13 | """ 14 | l=len(lists) 15 | if l==0: 16 | return None 17 | if l==1: 18 | return lists[0] 19 | left=self.mergeKLists(lists[:l/2]) 20 | right=self.mergeKLists(lists[l/2:]) 21 | ans=ListNode(0) 22 | node=ans 23 | while left or right: 24 | node.next=left if not right or (left and left.valnums[start]: 20 | end=i 21 | arrays=nums[start:end]+nums[end+1:] 22 | arrays.sort() 23 | nums[start]=nums[end] 24 | for i in range(start+1,len(nums)): 25 | nums[i]=arrays[i-start-1] -------------------------------------------------------------------------------- /python/034. Search for a Range.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def searchRange(self, nums, target): 5 | """ 6 | :type nums: List[int] 7 | :type target: int 8 | :rtype: List[int] 9 | """ 10 | arrays=self.search(nums,0,len(nums)-1,target) 11 | return [arrays[0],arrays[-1]] if len(arrays)>0 else [-1,-1] 12 | def search(self,nums,s,e,target): 13 | if s>e: 14 | return [] 15 | if s==e and nums[s]==target: 16 | return [s] 17 | m=(s+e)/2 18 | if nums[m]target: 21 | return self.search(nums,s,m-1,target) 22 | else: 23 | arrays=self.search(nums,s,m-1,target) 24 | arrays.extend([m]) 25 | arrays.extend(self.search(nums,m+1,e,target)) 26 | return arrays -------------------------------------------------------------------------------- /python/035. Search Insert Position.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def searchInsert(self, nums, target): 5 | """ 6 | :type nums: List[int] 7 | :type target: int 8 | :rtype: int 9 | """ 10 | if targetnums[end]: 14 | return end+1 15 | start=0 16 | while start=state[-1]: 14 | if num==target: 15 | yield [num] 16 | elif num0 and aans): 14 | ans=sum 15 | if sum<0: 16 | sum=0 17 | return ans -------------------------------------------------------------------------------- /python/054. Spiral Matrix.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def spiralOrder(self, matrix): 5 | """ 6 | :type matrix: List[List[int]] 7 | :rtype: List[int] 8 | """ 9 | mstep=len(matrix) 10 | if mstep==0: 11 | return [] 12 | nstep=len(matrix[0]) 13 | direction=0 14 | x=0 15 | y=-1 16 | ans=[] 17 | while mstep>0 and nstep>0: 18 | if direction%2==0: 19 | for i in range(1,nstep+1): 20 | y+= 1 if direction%4==0 else -1 21 | ans.append(matrix[x][y]) 22 | mstep-=1 23 | else: 24 | for i in range(1,mstep+1): 25 | x+= 1 if direction%4==1 else -1 26 | ans.append(matrix[x][y]) 27 | nstep-=1 28 | direction+=1 29 | return ans -------------------------------------------------------------------------------- /python/055. Jump Game.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def canJump(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: bool 8 | """ 9 | nums[-1]=True 10 | index=len(nums)-2 11 | if index<0: 12 | return True 13 | while index>=0: 14 | length=nums[index] 15 | if index+length>=len(nums)-1: 16 | nums[index]=True 17 | else: 18 | flag=False 19 | for i in range(1,length+1): 20 | if nums[index+i]: 21 | flag=True 22 | break 23 | nums[index]=flag 24 | index-=1 25 | return nums[0] -------------------------------------------------------------------------------- /python/057. Insert Interval.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for an interval. 4 | class Interval(object): 5 | def __init__(self, s=0, e=0): 6 | self.start = s 7 | self.end = e 8 | 9 | class Solution(object): 10 | def insert(self, intervals, newInterval): 11 | """ 12 | :type intervals: List[Interval] 13 | :type newInterval: Interval 14 | :rtype: List[Interval] 15 | """ 16 | if len(intervals)==0: 17 | return [newInterval] 18 | ns=newInterval.start 19 | ne=newInterval.end 20 | start=-1 21 | end=-1 22 | for i in range(len(intervals)): 23 | if start==-1: 24 | e=intervals[i].end 25 | if e>=ns: 26 | start=i 27 | s=intervals[i].start 28 | if s<=ne: 29 | end=i 30 | else: 31 | break 32 | if start==-1: 33 | return intervals+[newInterval] 34 | if end==-1: 35 | return [newInterval]+intervals 36 | ansStart=intervals[start].start if intervals[start].startnewInterval.end else newInterval.end 38 | intervals[start:end+1]=[Interval(ansStart,ansEnd)] 39 | return intervals -------------------------------------------------------------------------------- /python/058. Length of Last Word.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def lengthOfLastWord(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | strs=s.split(' ') 10 | for i in range(len(strs)-1,-1,-1): 11 | if len(strs[i])!=0 : return len(strs[i]) 12 | return 0 -------------------------------------------------------------------------------- /python/059. Spiral Matrix II.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def generateMatrix(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[List[int]] 8 | """ 9 | ans= [[0 for col in range(n)] for row in range(n)] 10 | step=n 11 | direction=x=a=0 12 | y=-1 13 | while step>0: 14 | for i in range(1,step+1): 15 | a+=1 16 | if direction%2==0: 17 | y+= 1 if direction%4==0 else -1 18 | else: 19 | x+= 1 if direction%4==1 else -1 20 | ans[x][y]=a 21 | if direction%2==0: 22 | step-=1 23 | direction+=1 24 | return ans -------------------------------------------------------------------------------- /python/060. Permutation Sequence.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def getPermutation(self, n, k): 5 | """ 6 | :type n: int 7 | :type k: int 8 | :rtype: str 9 | """ 10 | nums=range(1,n+1) 11 | pro=1 12 | ans="" 13 | k-=1 14 | for num in nums: 15 | pro*=num 16 | while len(nums)>0: 17 | pro/=len(nums) 18 | i=k/(pro) 19 | ans+=str(nums[i]) 20 | nums[i:i+1]=[] 21 | k-=i*pro 22 | return ans -------------------------------------------------------------------------------- /python/061. Rotate List.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for singly-linked list. 4 | # class ListNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.next = None 8 | 9 | class Solution(object): 10 | def rotateRight(self, head, k): 11 | """ 12 | :type head: ListNode 13 | :type k: int 14 | :rtype: ListNode 15 | """ 16 | length=self.getLength(head) 17 | if not head or length==0 or k%length==0: 18 | return head 19 | else: 20 | k=k%length 21 | node=head 22 | while length-k>1: 23 | node=node.next 24 | length-=1 25 | end=self.getEndNode(head) 26 | end.next=head 27 | ans=node.next 28 | node.next=None 29 | return ans 30 | def getLength(self,head): 31 | ans=0 32 | while head: 33 | ans+=1 34 | head=head.next 35 | return ans 36 | def getEndNode(self,head): 37 | while head.next: 38 | head=head.next 39 | return head -------------------------------------------------------------------------------- /python/062. Unique Paths.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def uniquePaths(self, m, n): 5 | """ 6 | :type m: int 7 | :type n: int 8 | :rtype: int 9 | """ 10 | matrix= [([0] * n) for i in range(m)] 11 | for i in range(m): 12 | for j in range(n): 13 | if i==0 or j==0: 14 | matrix[i][j]=1 15 | else: 16 | matrix[i][j]=matrix[i-1][j]+matrix[i][j-1] 17 | return matrix[m-1][n-1] -------------------------------------------------------------------------------- /python/063. Unique Paths II.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def uniquePathsWithObstacles(self, obstacleGrid): 5 | """ 6 | :type obstacleGrid: List[List[int]] 7 | :rtype: int 8 | """ 9 | m=len(obstacleGrid) 10 | n=len(obstacleGrid[0]) 11 | matrix= [([0] * n) for i in range(m)] 12 | print 'matrix[0][0]='+str(matrix[0][0]) 13 | for i in range(m): 14 | for j in range(n): 15 | if obstacleGrid[i][j]==1: 16 | matrix[i][j]=0 17 | elif i==0 and j==0: 18 | matrix[0][0]=1-obstacleGrid[0][0] 19 | else: 20 | #负数是反向读第一个,为0,不影响结果 21 | matrix[i][j]=matrix[i-1][j]+matrix[i][j-1] 22 | return matrix[m-1][n-1] 23 | 24 | -------------------------------------------------------------------------------- /python/064. Minimum Path Sum.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def minPathSum(self, grid): 5 | """ 6 | :type grid: List[List[int]] 7 | :rtype: int 8 | """ 9 | m=len(grid) 10 | n=len(grid[0]) 11 | ans=[[0 for col in range(n)] for row in range(m)] 12 | for i in range(m): 13 | for j in range(n): 14 | ans[i][j]+=grid[i][j] 15 | if i!=0 and j!=0: 16 | ans[i][j]+=min(ans[i-1][j],ans[i][j-1]) 17 | elif i!=0: 18 | ans[i][j]+=ans[i-1][j] 19 | elif j!=0: 20 | ans[i][j]+=ans[i][j-1] 21 | print ans 22 | return ans[m-1][n-1] -------------------------------------------------------------------------------- /python/067. Add Binary.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def addBinary(self, a, b): 5 | """ 6 | :type a: str 7 | :type b: str 8 | :rtype: str 9 | """ 10 | flag=False 11 | la=len(a) 12 | lb=len(b) 13 | l=max(la,lb) 14 | ans='' 15 | for i in range(1,l+1): 16 | t=(0 if i>la else int(a[-i])) + (0 if i>lb else int(b[-i])) + (1 if flag else 0) 17 | ans=str(t%2)+ans 18 | flag=t/2==1 19 | return ('1' if flag else '') +ans -------------------------------------------------------------------------------- /python/068. Text Justification.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def fullJustify(self, words, maxWidth): 5 | """ 6 | :type words: List[str] 7 | :type maxWidth: int 8 | :rtype: List[str] 9 | """ 10 | ansList=[] 11 | a=[] 12 | l=maxWidth 13 | for word in words: 14 | if len(word)<=l: 15 | a.append(word) 16 | l-=(len(word)+1) 17 | else: 18 | l+=len(a) 19 | if len(a)==1: 20 | text=a[0]+' '*l 21 | ansList.append(text) 22 | else: 23 | eachSpaceLength=l/(len(a)-1) 24 | extra=l%(len(a)-1) 25 | text=a[0] 26 | for i in range(1,len(a)): 27 | text+=(' '*(eachSpaceLength+(1 if i<=extra else 0))+a[i]) 28 | ansList.append(text) 29 | l=maxWidth-len(word)-1 30 | a=[word] 31 | if len(a)!=0: 32 | text='' 33 | for word in a: 34 | text+=(word+' ') 35 | text=text[:-1]+' '*(l+1) 36 | ansList.append(text) 37 | return ansList -------------------------------------------------------------------------------- /python/069. Sqrt(x).py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | import math 4 | class Solution(object): 5 | def mySqrt(self, x): 6 | """ 7 | :type x: int 8 | :rtype: int 9 | """ 10 | return int(math.sqrt(x)) -------------------------------------------------------------------------------- /python/070. Climbing Stairs.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def climbStairs(self, n): 5 | """ 6 | :type n: int 7 | :rtype: int 8 | """ 9 | if n<3: 10 | return n 11 | ans=[] 12 | ans.append(1) 13 | ans.append(2) 14 | for i in range(2,n): 15 | ans.append(ans[-1]+ans[-2]) 16 | return ans[-1] -------------------------------------------------------------------------------- /python/072. Edit Distance.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def minDistance(self, word1, word2): 5 | """ 6 | :type word1: str 7 | :type word2: str 8 | :rtype: int 9 | """ 10 | l1=len(word1) 11 | l2=len(word2) 12 | dict=[[0 for col in range(l1+1)] for row in range(l2+1)] 13 | for x in range(l2+1): 14 | for y in range(l1+1): 15 | if x*y==0: 16 | dict[x][y]=max(x,y) 17 | else: 18 | dict[x][y]=dict[x-1][y-1] if word1[y-1]==word2[x-1] else (1+min(dict[x-1][y],dict[x][y-1],dict[x-1][y-1])) 19 | return dict[-1][-1] -------------------------------------------------------------------------------- /python/073. Set Matrix Zeroes.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def setZeroes(self, matrix): 5 | """ 6 | :type matrix: List[List[int]] 7 | :rtype: void Do not return anything, modify matrix in-place instead. 8 | """ 9 | #列 10 | n=[1 for col in range(len(matrix[0]))] 11 | #行 12 | m=[1 for row in range(len(matrix))] 13 | for i in range(len(matrix)): 14 | for j in range(len(matrix[i])): 15 | if matrix[i][j]==0: 16 | n[j]=0 17 | m[i]=0 18 | for i in range(len(matrix)): 19 | for j in range(len(matrix[i])): 20 | if m[i]==0 or n[j]==0: 21 | matrix[i][j]=0 -------------------------------------------------------------------------------- /python/074. Search a 2D Matrix.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def searchMatrix(self, matrix, target): 5 | """ 6 | :type matrix: List[List[int]] 7 | :type target: int 8 | :rtype: bool 9 | """ 10 | row=len(matrix) 11 | if row==0: 12 | return False 13 | col=len(matrix[0]) 14 | begin=0 15 | end=row*col 16 | while begintarget: 24 | end=middle 25 | else: 26 | begin=middle+1 27 | return False -------------------------------------------------------------------------------- /python/075. Sort Colors.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def sortColors(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: void Do not return anything, modify nums in-place instead. 8 | """ 9 | low=0 10 | mid=0 11 | high=len(nums)-1 12 | while mid<=high: 13 | if nums[mid]==2: 14 | nums[mid]=nums[high] 15 | nums[high]=2 16 | high-=1 17 | elif nums[mid]==1: 18 | mid+=1 19 | else: 20 | nums[low]=0 21 | if mid!=low: 22 | nums[mid]=1 23 | low+=1 24 | mid+=1 25 | print nums -------------------------------------------------------------------------------- /python/077. Combinations.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def combine(self, n, k): 5 | """ 6 | :type n: int 7 | :type k: int 8 | :rtype: List[List[int]] 9 | """ 10 | nums=range(n+1) 11 | nums.remove(0) 12 | return list(self.f(nums,k,[])) 13 | def f(self,nums,k,state): 14 | for num in nums: 15 | if len(state)==0 or num>state[-1]: 16 | if len(state)==k-1: 17 | yield [num] 18 | else: 19 | for result in self.f(nums,k,state+[num]): 20 | yield [num]+result -------------------------------------------------------------------------------- /python/078. Subsets.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def subsets(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[List[int]] 8 | """ 9 | return [[]]+list(self.f(nums,[])) 10 | 11 | def f(self,nums,state): 12 | """ 13 | :type nums: List[int] 14 | :type state: List[int] 15 | :rtype: List[int] 16 | """ 17 | for num in nums: 18 | if len(state)==0 or num>state[-1]: 19 | yield [num] 20 | for result in self.f(nums,state+[num]): 21 | yield [num]+result -------------------------------------------------------------------------------- /python/080. Remove Duplicates from Sorted Array II.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def removeDuplicates(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: int 8 | """ 9 | if len(nums)<3: 10 | return len(nums) 11 | sign=nums[0] 12 | flag=False 13 | i=1 14 | while inums2[sn]: 20 | nums1[sm+1:m+1]=nums1[sm:m] 21 | nums1[sm]=nums2[sn] 22 | m+=1 23 | sn+=1 24 | sm+=1 -------------------------------------------------------------------------------- /python/089. Gray Code.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def grayCode(self, n): 5 | """ 6 | :type n: int 7 | :rtype: List[int] 8 | """ 9 | if n==0: 10 | return [0] 11 | else: 12 | ans=self.grayCode(n-1) 13 | return ans+[pow(2,n-1)+x for x in ans[::-1]] -------------------------------------------------------------------------------- /python/090. Subsets II.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def subsetsWithDup(self, nums): 5 | """ 6 | :type nums: List[int] 7 | :rtype: List[List[int]] 8 | """ 9 | nums.sort() 10 | index=list(self.f(nums,[])) 11 | ans=[[]] 12 | for ind in index: 13 | a=[] 14 | for i in ind: 15 | a.append(nums[i]) 16 | if a not in ans: 17 | ans.append(a) 18 | return ans 19 | 20 | def f(self,nums,state): 21 | """ 22 | :type nums: List[int] 23 | :type state: List[int] 24 | :rtype: List[int] 25 | """ 26 | for i in range(len(nums)): 27 | if len(state)==0 or i>state[-1]: 28 | yield [i] 29 | for result in self.f(nums,state+[i]): 30 | yield [i]+result -------------------------------------------------------------------------------- /python/091. Decode Ways.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def numDecodings(self, s): 5 | """ 6 | :type s: str 7 | :rtype: int 8 | """ 9 | l=len(s) 10 | if l==0: 11 | return 0 12 | if l==1: 13 | return 0 if s=='0' else 1 14 | ans=[0]*l 15 | ans[-1]=(1 if int(s[-1])!=0 else 0) 16 | ans[-2]=0 if int(s[-2])==0 else (1 if int(s[-2:])<27 else 0)+ans[-1] 17 | i=l-3 18 | while i>=0: 19 | ans[i]=0 if int(s[i])==0 else (ans[i+1]+(ans[i+2] if int(s[i:i+2])<27 else 0)) 20 | i-=1 21 | return ans[0] 22 | -------------------------------------------------------------------------------- /python/093. Restore IP Addresses.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def restoreIpAddresses(self, s): 5 | """ 6 | :type s: str 7 | :rtype: List[str] 8 | """ 9 | return list(self.f(s,'',0)) 10 | def f(self,s,state,num): 11 | if num==4: 12 | if len(s)==0: 13 | yield '' 14 | if num<4: 15 | if len(s)>0: 16 | if s[0]=='0': 17 | for result in self.f(s[1:],state+'.0',num+1): 18 | yield '0'+('.'+result if len(result)!=0 else '') 19 | else: 20 | for j in range(1,min(3,len(s))+1): 21 | i=int(s[:j]) 22 | if i>=0 and i<256: 23 | for result in self.f(s[j:],state+'.'+str(i),num+1): 24 | yield str(i)+('.'+result if len(result)!=0 else '') -------------------------------------------------------------------------------- /python/094. Binary Tree Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for a binary tree node. 4 | # class TreeNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | class Solution(object): 11 | def inorderTraversal(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: List[int] 15 | """ 16 | if root is None: 17 | return [] 18 | ans=[] 19 | ans.extend(self.inorderTraversal(root.left)) 20 | ans.append(root.val) 21 | ans.extend(self.inorderTraversal(root.right)) 22 | return ans -------------------------------------------------------------------------------- /python/096. Unique Binary Search Trees.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def __init__(self): 5 | self.map={} 6 | def numTrees(self, n): 7 | """ 8 | :type n: int 9 | :rtype: int 10 | """ 11 | if n<=1 : 12 | return 1 13 | if n not in self.map: 14 | ans=0 15 | for i in range(0,n): 16 | ans+=(self.numTrees(i)*self.numTrees(n-1-i)) 17 | self.map[n]=ans 18 | else : 19 | ans=self.map[n] 20 | return ans -------------------------------------------------------------------------------- /python/097. Interleaving String.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | class Solution(object): 4 | def isInterleave(self, s1, s2, s3): 5 | """ 6 | :type s1: str 7 | :type s2: str 8 | :type s3: str 9 | :rtype: bool 10 | """ 11 | l1=len(s1) 12 | l2=len(s2) 13 | if l1+l2!=len(s3): 14 | return False 15 | matrix=[[False for col in range(l1+1)] for row in range(l2+1)] 16 | matrix[l2][l1]=True 17 | for i in range(1,l1+1): 18 | ans=s1[-i]==s3[-i] 19 | if ans: 20 | matrix[l2][l1-i]=True 21 | else: 22 | break 23 | for i in range(1,l2+1): 24 | ans=s2[-i]==s3[-i] 25 | if ans: 26 | matrix[l2-i][l1]=True 27 | else: 28 | break 29 | for i in range(l2-1,-1,-1): 30 | for j in range(l1-1,-1,-1): 31 | matrix[i][j]=(s2[i]==s3[i+j] and matrix[i+1][j]) or (s1[j]==s3[i+j] and matrix[i][j+1]) 32 | return matrix[0][0] -------------------------------------------------------------------------------- /python/098. Validate Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for a binary tree node. 4 | # class TreeNode(object): 5 | # def __init__(self, x): 6 | # self.val = x 7 | # self.left = None 8 | # self.right = None 9 | 10 | class Solution(object): 11 | def isValidBST(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: bool 15 | """ 16 | if root is None: 17 | return True 18 | leftVal=self.maxNodeVal(root.left) 19 | rightVal=self.minNodeVal(root.right) 20 | return False if (leftVal and leftVal>=root.val) or (rightVal and rightVal<=root.val) else self.isValidBST(root.left) and self.isValidBST(root.right) 21 | def maxNodeVal(self,root): 22 | if root is None: 23 | return None 24 | midVal=root.val 25 | leftVal=self.maxNodeVal(root.left) 26 | rightVal=self.maxNodeVal(root.right) 27 | return max(leftVal if leftVal else midVal,rightVal if rightVal else midVal,midVal) 28 | def minNodeVal(self,root): 29 | if root is None: 30 | return None 31 | midVal=root.val 32 | leftVal=self.minNodeVal(root.left) 33 | rightVal=self.minNodeVal(root.right) 34 | return min(leftVal if leftVal else midVal,rightVal if rightVal else midVal,midVal) -------------------------------------------------------------------------------- /python/099. Recover Binary Search Tree.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'xuxuan' 3 | # Definition for a binary tree node. 4 | class TreeNode(object): 5 | def __init__(self, x): 6 | self.val = x 7 | self.left = None 8 | self.right = None 9 | class Solution(object): 10 | _pre=_m1=_m2=None 11 | def recoverTree(self, root): 12 | """ 13 | :type root: TreeNode 14 | :rtype: void Do not return anything, modify root in-place instead. 15 | """ 16 | self._pre=self._m1=self._m2=None 17 | self.findMistakes(root) 18 | val=self._m1.val 19 | self._m1.val=self._m2.val 20 | self._m2.val=val 21 | def findMistakes(self,root): 22 | if not root: 23 | return 24 | if root.left: 25 | self.findMistakes(root.left) 26 | if self._pre and root.val