78 Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
|
|
这一题相当于找所有nums的所有子集。我们可以知道,一共会有2^(nums.length)个子集。如何判断某个数在某个子集有没有出现呢。我们可以用一个mask。
n位的二进制数,有2^n种可能(0~1<<(nums.length)),对于每一种可能,如果在第j位的数是1,说明第nums[j]存在于该可能(子集)中。
时间复杂度是2^n*n
|
|
337 House Robber III
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
|
|
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
|
|
Maximum amount of money the thief can rob = 4 + 5 = 9.
你说这个贼还能再可怜一些吗。偷个东西还得做算法题。
我现在一看到树,第一反应就是dfs。对于每一个node,有两种可能,就是偷或者不偷。假设偷了currentNode,我们就不能偷他的左右孩子节点。但是如果不偷currentNode,对于左右孩子节点,我们就可以选择偷或者不偷(选择最优解)。所以对于每个node,我们会有两个两个状态:res[0]表示偷了当前节点;res[1]表示没有偷当前节点。
所以res[0] = root.val + left_res[1]+right_res[1];
res[1] = Math.max(left_res[0],left_res[1])+Math.max(right_res[0],right_res[1]);
|
|
494 Target Sum
You are given a list of non-negative integers, a1, a2, …, an, and a target, S. Now you have 2 symbols +
and -
. For each integer, you should choose one from +
and -
as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
|
|
Note:
- The length of the given array is positive and will not exceed 20.
- The sum of elements in the given array will not exceed 1000.
- Your output answer is guaranteed to be fitted in a 32-bit integer.
这一题,又是可以画树状图。左路径是乘-1,右路径是乘1。
每次往后推进一个数,到最后一个数的时候判断,如果满足条件,就把全局变量count++。
|
|
但是zhengyu He同学表示这样做复杂度太高,O(n^2)。所以还是得改啊……