-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
51 lines (48 loc) · 1.27 KB
/
Solution.cs
File metadata and controls
51 lines (48 loc) · 1.27 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
public class Solution
{
public bool ValidPartition(int[] nums)
{
int n = nums.Length;
int[] memo = new int[n];
Array.Fill(memo, -1);
return DP(0, nums, memo);
}
bool DP(int pos, int[] nums, int[] memo)
{
if (pos == nums.Length) return true;
if (pos + 2 > nums.Length) return false;
if (memo[pos] != -1) return memo[pos] == 1;
if (nums.Length - pos >= 2)
{
if (nums[pos] == nums[pos + 1])
{
if (DP(pos + 2, nums, memo))
{
memo[pos] = 1;
return true;
}
}
}
if (nums.Length - pos >= 3)
{
if (nums[pos] == nums[pos + 1] && nums[pos] == nums[pos + 2])
{
if (DP(pos + 3, nums, memo))
{
memo[pos] = 1;
return true;
}
}
if (nums[pos] == nums[pos + 1] - 1 && nums[pos] == nums[pos + 2] - 2)
{
if (DP(pos + 3, nums, memo))
{
memo[pos] = 1;
return true;
}
}
}
memo[pos] = 0;
return false;
}
}