General

Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

public int climbStairs(int n) {
    if (n == 0 || n == 1) return n;
    int[] f = new int[n+1];
    f[0] = 1;
    f[1] = 1;
    for (int i=2; i<=n; i++){
        f[i] = f[i-1] + f[i-2];
    }
    return f[n];
}

Decode Ways

A message containing letters from A-Z is being encoded to numbers using the following mapping:

'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it.

  • Func: f[i] = f[i-1](if s[i-1]!='0')+f[i-2](if(s[i-2]s[i-1] == '10'-'26'))

  • Init f[0]=f[1]=1

  • Ans f[n]

300 Longest Increasing Subsequence

Given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. This subsequence is not necessarily contiguous, or unique.

Example For [5, 4, 1, 2, 3], the LIS is [1, 2, 3], return 3 For [4, 2, 4, 5, 3, 7], the LIS is [2, 4, 5, 7], return 4

  • Brute Time O(2^n)

  • State: f[i] = LIS in index i

  • Init: f[0...i] = 1

  • function: f[i] = max{f[j]+1}, j<i && num[j]<num[i]

  • Ans: max{f[0...i]}

  • Time O(n^2), Space O(n)

53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

  • dp[i]: in nums[0:i], the maximum subarray containing nums[i]

  • dp[i] = max(dp[i-1]+nums[i], nums[i])

152. Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

  • max[i]: in nums[0:i], the maximum product subarray containing nums[i]

  • Maintain a min and a max variable, if nums[i] is negative, swap them

  • ans[i] = max(max[i-1]+nums[i], nums[i])

96. Unique Binary Search Tree

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

[1, 2, 3, 4, 5, 6, 7] with 3 as the root, left subsequence [1, 2] and the right subsequence [4, 5, 6, 7], dp[2] * dp[4] to dp[7]

95. Unique Binary Search Tree II

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

1235. Maximum Profit in Job Scheduling

We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

  • DP + binary search

Last updated

Was this helpful?