当前位置:网站首页>324. swing sort II / Sword finger offer II 102 Target value of addition and subtraction
324. swing sort II / Sword finger offer II 102 Target value of addition and subtraction
2022-06-29 08:23:00 【Biqiliang】
324. Swing sort II【 Medium question 】【 A daily topic 】
Ideas :
Learning problem solving .
【Nick~Hot topic 】 Relatively simple double pointer idea !
Code :
class Solution {
public void wiggleSort(int[] nums) {
int n = nums.length;
// Copy nums The array is copy
int[] copy = Arrays.copyOf(nums,n);
// Yes copy Array to sort
Arrays.sort(copy);
// take copy The array is divided into two parts , Both the left side and the right side increase in turn ( Possible equality ), The left side is all smaller than the right side , Definition left Is the right endpoint pointer on the left ,right Is the right endpoint pointer on the right
int left = (n - 1) / 2,right = n - 1;
// Arrange the left and right elements in reverse order , Then cross update the elements of the array , Even subscripts place the left elements in reverse order , Odd subscripts place the right elements in reverse order
for (int i = 0; i < n; i++) {
if (i % 2 == 0){
// Even subscripts are placed in reverse order on the left element
nums[i] = copy[left--];
}else {
// Odd subscripts are placed in reverse order on the right element
nums[i] = copy[right--];
}
}
}
}
The finger of the sword Offer II 102. The target value of addition and subtraction 【 Medium question 】
Ideas :【 Dynamic programming 】
First of all, we need to re model the problem , Transform the problem into a dynamic programming problem .
Write the first order according to the solution dp And second order dp as follows .
Code :【 Second order dp】
class Solution {
public int findTargetSumWays(int[] nums, int target) {
/** * According to the solution to the problem , We need to change the direction of solving this problem first , Then use dynamic programming to solve . * Set the sum of the elements of the array to sum, Set the sum of the elements with a minus sign before the element to neg , Then the sum of the other elements with the plus sign is sum - neg, therefore * sum - neg - neg = target ==> neg = (sum-target)/2 * Because the elements in the array are non negative integers , therefore neg Must also be a non negative integer therefore sum - target Must be Nonnegative even number , If this condition is not satisfied Then return directly 0, Indicates that there is no expression that meets the requirements * After excluding special circumstances , because sum only , And you can find out ,target Given , So the question turns to Select any element in the array , Find the sum of the selected elements equal to sum-target Number of alternatives */
int sum = Arrays.stream(nums).sum();
if (sum - target < 0 || (sum - target) % 2 != 0){
return 0;
}
int n = nums.length,neg = (sum - target) / 2;
// Definition dp Array dp[i][j] Express Before the array i Elements Select any number of elements and by j Number of alternatives
int[][] dp = new int[n+1][neg+1];
// The boundary conditions Don't select element , Then the element and must be 0, Then when the required sum is 0 when , This is a plan , When required and not for 0 when , No scheme meets the requirements dp[0][j] = 0(j!=0) Keep the default value
dp[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= neg; j++) {
// If j >= nums[i-1] So the current element nums[i-1] No choice , Both cases should be considered
if (j >= nums[i-1]){
// No election The current number of schemes depends on dp[i-1][j]
// choose The current number of schemes depends on dp[i-1][j-nums[i]]
dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i-1]];
}else {
// If j < nums[i-1] So the current element nums[i-1] You must not choose , Because I have chosen and must surpass j
dp[i][j] = dp[i-1][j];
}
}
}
//dp[n][neg] That is to say All elements of the array And for neg Number of alternatives
return dp[n][neg];
}
}
Code :【 First order dp】
class Solution {
public int findTargetSumWays(int[] nums, int target) {
/** * According to the solution to the problem , We need to change the direction of solving this problem first , Then use dynamic programming to solve . * Set the sum of the elements of the array to sum, Set the sum of the elements with a minus sign before the element to neg , Then the sum of the other elements with the plus sign is sum - neg, therefore * sum - neg - neg = target ==> neg = (sum-target)/2 * Because the elements in the array are non negative integers , therefore neg Must also be a non negative integer therefore sum - target Must be Nonnegative even number , If this condition is not satisfied Then return directly 0, Indicates that there is no expression that meets the requirements * After excluding special circumstances , because sum only , And you can find out ,target Given , So the question turns to Select any element in the array , Find the sum of the selected elements equal to sum-target Number of alternatives */
int sum = Arrays.stream(nums).sum();
if (sum - target < 0 || (sum - target) % 2 != 0){
return 0;
}
int n = nums.length,neg = (sum - target) / 2;
// Definition dp Array dp[j] Express Before the array i(i Dynamically adjust according to the actual situation , For the initial 0, And then from 1 Gradually increasing ) Elements Take the sum of any number of elements as j Number of alternatives
int[] dp = new int[neg+1];
// The boundary conditions And for 0 Before 0 The number of schemes with elements is 1
dp[0] = 1;
for (int i = 0; i < n; i++) {
// Gradually expand the window of optional elements
for (int j = neg; j >= nums[i]; j--) {
// In order to prevent dp[j-nums[i]] It is updated during calculation , So we traverse in reverse order dp Array
// Traversal in reverse order j == nums[i] The deadline is because j<nums[i] when ,dp[j] = dp[j]
// The transfer equation is as follows :
dp[j] = dp[j] + dp[j-nums[i]];
}
}
// At the end of the loop ,i by n, So at this time dp[neg] That is to say All elements of the array Take the sum of any number of elements as neg Number of alternatives
return dp[neg];
}
}
边栏推荐
- Notes mosaïque
- 智能硬件evt dvt pvt mp
- Simulation time and bag operation in ROS
- 互斥量互斥锁
- Soliciting articles and contributions - building a blog environment with a lightweight application server
- 在colaboratory上云端使用GPU训练(以YOLOv5举例)
- NP5 格式化输出(三)
- Program debugging - debug/release version
- [eye of depth wuenda machine learning operation class phase IV] logic regression programming implementation
- U盘内存卡数据丢失怎么恢复,这样操作也可以
猜你喜欢

Thread pool operations in cartographer

PostgreSQL installation: the database cluster initialization failed, stack hbuilder installation

About the many to many cascading insertion of sqlsugar (the ID of the collection attribute cannot be obtained, so the intermediate table cannot be maintained)

Binary search tree

Stm32 usart+dma usage based on Hal Library

Mongodb- connect to the database using the mongo/mongosh command line

solidity部署和验证代理合约
![[6G] collation of white paper on computing network technology](/img/a3/8e60eef55ebcd91fa6188722c87a70.png)
[6G] collation of white paper on computing network technology

802.11--802.11n协议 PHY

Excel中VLOOKUP函数简易使用——精确匹配或近似匹配数据
随机推荐
Reflection - project management thinking of small and medium-sized companies - make the products first and the functions first
Automatic operation and maintenance management platform - construction and daily use of SPuG
Debugging nocturnal simulator with ADB command
VMware vcenter/esxi series vulnerability summary
Binary search tree
Friends, static keywords, static methods, and relationships between objects
[quantitative investment system]django realizes screening and paging from the database
《乔布斯传》英文原著重点词汇笔记(八)【 chapter six 】
语音信号处理-基础(一):声学基础知识
PaddleNLP通用信息抽取模型:UIE【信息抽取{实体关系抽取、中文分词、精准实体标。情感分析等}、文本纠错、问答系统、闲聊机器人、定制训练】
Introduction to taro
PHP 7.1.13 版本,在使用过程中发现 浮点类型 数据经过 json_encode 之后会出现精度问题
Soliciting articles and contributions - building a blog environment with a lightweight application server
js:Array. Reduce cumulative calculation and array consolidation
aws elastic beanstalk入门之简单使用
SQL Server enable CDC
考研英语易混词整理【闪过】
Thread pool operations in cartographer
Time operation - time format conversion
C compiler - implicit function declaration