1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 国科大-计算机算法设计与分析-卜东波作业2

国科大-计算机算法设计与分析-卜东波作业2

时间:2019-05-19 11:33:40

相关推荐

国科大-计算机算法设计与分析-卜东波作业2

题目一

Money Robbing

A robber is planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.What if all houses are arranged in a circle?

算法思想:该题是要求能抢的最大钱数,规定相邻的房子不能同事去抢。所以其表达式为dp[i]=max{dp[i],dp[j]+nums[i]}其中0<=j<i-1。此表达式可以计算出投到这一家时所投的最多钱数,还需要用一个max变量去记录所能偷取的最多钱数

class Solution {public int rob(int[] nums) {int[] dp = new int[nums.length];int max = nums[0];dp[0] = nums[0];for (int i = 0; i < nums.length; i++) {if (i == 1) {dp[i] = nums[i];}for (int j = 0; j < i - 1; j++) {dp[i] = Math.max(dp[i], dp[j] + nums[i]);}if (dp[i] > max)max = dp[i];}return max;}}

时间复杂度:O(n^2)

空间复杂度:O(n)

题目二

Ugly Number

An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.Given an integer n, return the 𝒏𝒕𝒉 ugly number.

算法思想:因为丑数是因子只为2,3,5的数,所以丑数一定是一个小的丑数去乘以这三个因子。得出的状态方程为dp[i]=min(dp[a]×2,dp[b]×3,dp[c]×5),设a=b=c=1。当最小的值为dp[a]*2时令a++,b和c也是如此的变化,这样就可以实现dp数组是单调递增的。

class Solution {public int nthUglyNumber(int n) {int[] dp = new int[n];dp[0] = 1;int x = 0, y = 0, z = 0;for (int i = 1; i < n; i++) {int min =Math.min(Math.min(dp[x]*2,dp[y]*3),dp[z]*5) ;if (dp[x]*2 == min)x++;if (dp[y]*3 == min)y++;if (dp[z]*5 == min)z++;dp[i]=min;}return dp[n-1];}}

时间复杂度:O(n)

空间复杂度:O(n)

题目三

Largest Divisible Subset

Given a set of distinct positive integers, find the largest subset such that every pair (𝑆𝑖, 𝑆𝑗) of elements in this subset satisfies: 𝑆𝑖%𝑆𝑗 = 0 or 𝑆𝑗%𝑆𝑖 = 0. Please return the largest size of the subset.

Note: 𝑆𝑖%𝑆𝑗 = 0 means that 𝑆𝑖 is divisible by 𝑆𝑗

算法思想:首先我们先将得到的数组进行排序,因为如果一个数可以整数一个符合要求集合中的最大的数,则肯定可以整除这个集合的所有的数,那么这个数就可以加入集合当中。则加入的判定条件可以写为: if (nums[i] % nums[j] == 0&&dp[j]+1>dp[i])。本题主要的过程是如何回溯去找到符合要求的集合。我们只要找一个标记数组去记录就可以实现回溯。

class Solution {public List<Integer> largestDivisibleSubset(int[] nums) {Arrays.sort(nums);int[] dp = new int[nums.length];int[] ans = new int[nums.length];int max, flag;dp[0] = 1;max = 1;flag = 0;for (int i = 1; i < nums.length; i++) {dp[i] = 1;ans[i] = i;for (int j = 0; j < i; j++) {if (nums[i] % nums[j] == 0&&dp[j]+1>dp[i]) {dp[i] = dp[j] + 1;ans[i] = j;if (dp[i] > max) {max = dp[i];flag = i;}}}}System.out.println(max);List<Integer> ret = new ArrayList<Integer>();while (dp[flag] != 1) {ret.add(nums[flag]);flag = ans[flag];}ret.add(nums[flag]);Collections.sort(ret);return ret;}}

时间复杂度:O(n*logn)

空间复杂度:O(n)

.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。