2020-03-22
回溯算法:
static void Main(string[] args)
{
int[] nums = { 1, 2, 3 };
IList<IList<int>> xa = Subsets(nums);
Console.Write(xa);
Console.ReadKey();
}
//回溯法
private static IList<IList<int>> res;
private static void find(int[] nums, int begin, IList<int> pre)
{
// 没有显式的递归终止
res.Add(new List<int>(pre));// 注意:这里要 new 一下
for (int i = begin; i < nums.Length; i++)
{
pre.Add(nums[i]);
find(nums, i + 1, pre);
pre.RemoveAt(pre.Count - 1);// 组合问题,状态在递归完成后要重置
}
}
public static IList<IList<int>> Subsets(int[] nums)
{
int len = nums.Length;
res = new List<IList<int>>();
if (len == 0)
{
return res;
}
IList<int> pre = new List<int>();
find(nums, 0, pre);
return res;
}
2019年2月24日
public static IList<IList<int>> Subsets(int[] nums)
{
List<IList<int>> result = new List<IList<int>>();
result.Add(new List<int>());
Array.Sort(nums);
for (int i = 0; i < nums.Length; i++)
{
List<IList<int>> newResult = new List<IList<int>>();
foreach (var r in result)
{
List<int> nr = new List<int>(r);
nr.Add(nums[i]);
newResult.Add(nr);
}
result.AddRange(newResult);
}
return result;
}
c# 语法的 leetcode 78题
请将如下代码copy到控制台执行:
static void Main(string[] args)
{
string[] ns = new string[] { "1", "2", "3" };
List<string> ts = GetNum(ns);
for (int i = 0; i < ts.Count; i++)
{
Console.WriteLine(ts[i]);
}
Console.ReadKey();
}
private static List<string> GetNum(string[] nums)
{
int op = 0;
List<string> list = new List<string>();
for (int i = 0; i < nums.Length; i++)
{
list.Add("["+nums[i]+"]"); // 每当游标为当前的一个字符先加入 1、2、3 加入
//以当前的数为基数查找2个的
op++;
if (op<nums.Length)
{
list.Add("[" + nums[i] + "]" + "[" + nums[op] + "]");
}
int cp = op;
cp++;
if (cp<nums.Length)
{
list.Add("[" + nums[i] + "]" + "[" + nums[op] + "]" + "[" + nums[cp] + "]");
}
int pp = cp;
pp++;
if (pp < nums.Length)
{
list.Add("[" + nums[i] + "]" + "[" + nums[op] + "]" + "[" + nums[cp] + "]" + "[" + nums[pp] + "]");
}
}
list.Add("[]");
return list;
}
你会发现上面的功能虽然满足要求,但进限于在数组中存在三个数。
那么将上述代码找到规律遍是算法:
请用递归