[leetcode] Permutation Sequence

Question: The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): “123” “132” “213” “231” “312” “321” Given n and k, return the kth permutation sequence. Note: Given n will be between 1 and 9 […]

Read More

[leetcode] Gas Station

Question: There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one […]

Read More

[Leetcode] Flatten Binary Tree to Linked List

Problem: Given a binary tree, flatten it to a linked list in-place. [pastacode lang=”java” message=”” highlight=”” provider=”manual”] // use stack to store right public void flattenTree(TreeNode root) { if (root == null) return root; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode p = root; while (!stack.isEmpty()|| p != null) { if (p.right != null) stack.push(p.right); if […]

Read More

[Leetcode] Triangle

Problem: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [     [2],    [3,4],   [6,5,7],  [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 […]

Read More

[Leetcode] Binary Tree Level Order Traversal I && II

Problem Binary Tree Level Order Traversal I Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). Solution 1:  DFS, use variable to track depth, add node.val to according level sets [pastacode lang=”java” message=”” highlight=”” provider=”manual”] public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = […]

Read More

[Leetcode] Multiply Strings

Problem: Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative.   Solution: [pastacode lang=”java” message=”” highlight=”” provider=”manual”] public class Solution { public String multiply(String num1, String num2) { if (num1 == null || num2 == null) return "Invalid Input"; if (num1.equals("0") […]

Read More