FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Recursive/Partition.js at master · TheAlgorithms/JavaScript · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
JavaScript
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
5.8k
Star
34.2k
Code
Issues
21
Pull requests
192
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScript
/
Recursive
/
Partition.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
39 lines (30 loc) · 1.15 KB
Breadcrumbs
JavaScript
/
Recursive
/
Partition.js
Copy path
File metadata and controls
39 lines (30 loc) · 1.15 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
*
@function
canPartition
*
@description
Check whether it is possible to partition the given array into two equal sum subsets using recursion.
*
@param
{
number[]
} nums - The input array of numbers.
*
@param
{
number
} index - The current index in the array being considered.
*
@param
{
number
} target - The target sum for each subset.
*
@return
{
boolean
}.
*
@see
[Partition Problem](https://en.wikipedia.org/wiki/Partition_problem)
*/
const
canPartition
=
(
nums
,
index
=
0
,
target
=
0
)
=>
{
if
(
!
Array
.
isArray
(
nums
)
)
{
throw
new
TypeError
(
'Invalid Input'
)
}
const
sum
=
nums
.
reduce
(
(
acc
,
num
)
=>
acc
+
num
,
0
)
if
(
sum
%
2
!==
0
)
{
return
false
}
if
(
target
===
sum
/
2
)
{
return
true
}
if
(
index
>=
nums
.
length
||
target
>
sum
/
2
)
{
return
false
}
// Include the current number in the first subset and check if a solution is possible.
const
withCurrent
=
canPartition
(
nums
,
index
+
1
,
target
+
nums
[
index
]
)
// Exclude the current number from the first subset and check if a solution is possible.
const
withoutCurrent
=
canPartition
(
nums
,
index
+
1
,
target
)
return
withCurrent
||
withoutCurrent
}
export
{
canPartition
}
Back
|
FazBrowse Home
|
New Git URL