Skip to content

Commit b33e2b1

Browse files
committed
DP(dynamic programming)
1 parent 564d27a commit b33e2b1

7 files changed

+328
-0
lines changed

DP/ContinuousSubarraySln.cs

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace DP.Lib
8+
{
9+
// Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.
10+
11+
//Example 1:
12+
13+
//Input: [23, 2, 4, 6, 7], k=6
14+
//Output: True
15+
//Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
16+
17+
//Example 2:
18+
19+
//Input: [23, 2, 6, 4, 7], k=6
20+
//Output: True
21+
//Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.
22+
// Note:
23+
//The length of the array won’t exceed 10,000.
24+
//You may assume the sum of all the numbers is in the range of a signed 32-bit integer.
25+
public class ContinuousSubarraySln
26+
{
27+
private int[] _nums;
28+
private int _len;
29+
public bool CheckSubarraySum(int[] nums, int k)
30+
{
31+
_nums = nums;
32+
_len = nums.Length;
33+
calculator();
34+
for (int i = 0; i < _len; i++)
35+
for (int j = i + 1; j < _len; j++)
36+
{
37+
if (k == 0) //取余时一定注意,k不能为0!
38+
{
39+
if (rangeSum(i, j) == 0)
40+
return true;
41+
}
42+
else
43+
{
44+
if (rangeSum(i, j) % k == 0)
45+
return true;
46+
}
47+
}
48+
return false;
49+
}
50+
51+
private void calculator()
52+
{
53+
for (int i = 1; i < _len; i++)
54+
_nums[i] += _nums[i - 1];
55+
}
56+
57+
private int rangeSum(int i, int j)
58+
{
59+
if (i == 0)
60+
return _nums[j];
61+
return _nums[j] - _nums[i - 1];
62+
}
63+
}
64+
}

DP/DP.Lib.csproj

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
4+
<PropertyGroup>
5+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7+
<ProjectGuid>{C149A213-5599-4998-ADB4-23B80AAE270A}</ProjectGuid>
8+
<OutputType>Library</OutputType>
9+
<AppDesignerFolder>Properties</AppDesignerFolder>
10+
<RootNamespace>DP.Lib</RootNamespace>
11+
<AssemblyName>DP.Lib</AssemblyName>
12+
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
13+
<FileAlignment>512</FileAlignment>
14+
</PropertyGroup>
15+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
16+
<DebugSymbols>true</DebugSymbols>
17+
<DebugType>full</DebugType>
18+
<Optimize>false</Optimize>
19+
<OutputPath>bin\Debug\</OutputPath>
20+
<DefineConstants>DEBUG;TRACE</DefineConstants>
21+
<ErrorReport>prompt</ErrorReport>
22+
<WarningLevel>4</WarningLevel>
23+
</PropertyGroup>
24+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
25+
<DebugType>pdbonly</DebugType>
26+
<Optimize>true</Optimize>
27+
<OutputPath>bin\Release\</OutputPath>
28+
<DefineConstants>TRACE</DefineConstants>
29+
<ErrorReport>prompt</ErrorReport>
30+
<WarningLevel>4</WarningLevel>
31+
</PropertyGroup>
32+
<ItemGroup>
33+
<Reference Include="System" />
34+
<Reference Include="System.Core" />
35+
<Reference Include="System.Xml.Linq" />
36+
<Reference Include="System.Data.DataSetExtensions" />
37+
<Reference Include="Microsoft.CSharp" />
38+
<Reference Include="System.Data" />
39+
<Reference Include="System.Xml" />
40+
</ItemGroup>
41+
<ItemGroup>
42+
<Compile Include="ContinuousSubarraySln.cs" />
43+
<Compile Include="HouseRoberSln.cs" />
44+
<Compile Include="MajorityNumberSln.cs" />
45+
<Compile Include="MaximumSubarraySln.cs" />
46+
<Compile Include="Properties\AssemblyInfo.cs" />
47+
<Compile Include="RangeSumQuerySln.cs" />
48+
</ItemGroup>
49+
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
50+
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
51+
Other similar extension points exist, see Microsoft.Common.targets.
52+
<Target Name="BeforeBuild">
53+
</Target>
54+
<Target Name="AfterBuild">
55+
</Target>
56+
-->
57+
</Project>

DP/HouseRoberSln.cs

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace DP.Lib
8+
{
9+
// You are a professional robber 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.
10+
11+
//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.
12+
public class HouseRoberSln
13+
{
14+
//nums = {1, 8, 12 10, 9 }
15+
public int Rob(int[] nums)
16+
{
17+
int inCur = 0; //偷当前房子能获取的最大钱数
18+
int noInCur = 0;//不偷当前的房子能收获的最大钱数
19+
for (int i = 0; i < nums.Length; i++)
20+
{
21+
int tmp = nums[i] + noInCur; //偷 ith 房子,上一个房子就不能偷
22+
noInCur = Math.Max(inCur, noInCur); //如果不偷 ith 房子,则noInCur 等于偷 i-1 房子和不偷 i-1 房子的最大值
23+
inCur = tmp; //偷当前房子后的获取总钱数
24+
}
25+
return Math.Max(inCur, noInCur);
26+
}
27+
}
28+
}

DP/MajorityNumberSln.cs

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace DP.Lib
8+
{
9+
// Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
10+
11+
//You may assume that the array is non-empty and the majority element always exist in the array.
12+
public class MajorityNumberSln
13+
{
14+
//O(1)空间复杂度
15+
public int MajorityElement(int[] nums)
16+
{
17+
int major = nums[0];
18+
int count = 1;
19+
for (int i = 1; i < nums.Length; i++)
20+
{
21+
if (count == 0)
22+
{
23+
count++;
24+
major = nums[i];
25+
}
26+
else if (major == nums[i])
27+
count++;
28+
else
29+
count--; //此消彼长
30+
}
31+
return major;
32+
}
33+
34+
//hash table version
35+
public int MajorityElement2(int[] nums)
36+
{
37+
Dictionary<int, int> dict = new Dictionary<int, int>();
38+
int majorityElement = nums[0];
39+
foreach (var item in nums)
40+
{
41+
if (dict.ContainsKey(item))
42+
{
43+
dict[item]++;
44+
//注意是大于,而不是 大于或等于
45+
if (dict[item] > nums.Length / 2)
46+
majorityElement = item;
47+
}
48+
else
49+
dict.Add(item, 1);
50+
}
51+
return majorityElement;
52+
}
53+
54+
}
55+
}

DP/MaximumSubarraySln.cs

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace DP.Lib
8+
{
9+
// Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
10+
11+
//For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
12+
//the contiguous subarray [4,-1,2,1] has the largest sum = 6.
13+
public class MaximumSubarraySln
14+
{
15+
//a simple and fast method
16+
public int MaxSubArray(int[] nums)
17+
{
18+
int premax = nums[0]; //过去最大值
19+
int curmax = nums[0]; //当前最大值
20+
for (int i = 1; i < nums.Length; i++)
21+
{
22+
curmax = Math.Max(nums[i], nums[i] + curmax);
23+
premax = Math.Max(curmax, premax);
24+
}
25+
return premax;
26+
}
27+
public int MaxSubArrayTest(int[] nums)
28+
{
29+
int premax =nums[0]; //过去最大值
30+
int curmax = nums[0]; //当前最大值
31+
Console.WriteLine(string.Format("curmax,premax初始值等于{0}",curmax));
32+
for(int i=1;i<nums.Length;i++)
33+
{
34+
Console.WriteLine(string.Format("遍历值{0}",nums[i]));
35+
Console.WriteLine(string.Format("当前curmax等于{0}",curmax));
36+
if (nums[i] + curmax > nums[i])
37+
Console.WriteLine(string.Format("cumax接纳遍历值{0}变为{1}", nums[i], curmax+nums[i]));
38+
else
39+
Console.WriteLine(string.Format("curmax舍弃自己后等于遍历值{0}", nums[i]));
40+
curmax = Math.Max(nums[i], nums[i] + curmax);
41+
premax = Math.Max(curmax, premax);
42+
Console.WriteLine(string.Format("记忆数组连续元素的和最大值{0}\n", premax));
43+
}
44+
return premax;
45+
}
46+
}
47+
}

DP/Properties/AssemblyInfo.cs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// 有关程序集的常规信息通过以下
6+
// 特性集控制。更改这些特性值可修改
7+
// 与程序集关联的信息。
8+
[assembly: AssemblyTitle("DP.Lib")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("DP.Lib")]
13+
[assembly: AssemblyCopyright("Copyright © 2017")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// 将 ComVisible 设置为 false 使此程序集中的类型
18+
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19+
// 则将该类型上的 ComVisible 特性设置为 true。
20+
[assembly: ComVisible(false)]
21+
22+
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23+
[assembly: Guid("e992de28-218c-4724-ba8c-5f2987c3276a")]
24+
25+
// 程序集的版本信息由下面四个值组成:
26+
//
27+
// 主版本
28+
// 次版本
29+
// 生成号
30+
// 修订号
31+
//
32+
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33+
// 方法是按如下所示使用“*”:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]

DP/RangeSumQuerySln.cs

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace DP.Lib
8+
{
9+
// Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
10+
11+
//Example:
12+
//Given nums = [-2, 0, 3, -5, 2, -1]
13+
//sumRange(0, 2) -> 1
14+
//sumRange(2, 5) -> -1
15+
//sumRange(0, 5) -> -3
16+
// Note:
17+
//1. You may assume that the array does not change.
18+
//2. There are many calls to sumRange function.
19+
public class RangeSumQuerySln
20+
{
21+
public class NumArray
22+
{
23+
24+
private int[] _nums;
25+
public NumArray(int[] nums)
26+
{
27+
_nums = nums;
28+
for (int i = 1; i < _nums.Length; i++)
29+
_nums[i] += _nums[i - 1];
30+
}
31+
32+
public int SumRange(int i, int j)
33+
{
34+
if (i == 0)
35+
return _nums[j];
36+
37+
return _nums[j] - _nums[i - 1];
38+
}
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)