- class Program
- {
- private static List<string> TargetRoad = new List<string>(0);
- private static List<string> PassedRoad = new List<string>(0);
- private static List<int> InputArray = new List<int>();
- private static string road = string.Empty;
- static void Main()
- {
- for (int Index = 1; Index <= 20; Index++)
- {
- InputArray.Add(Index);
- }
- TraceBack(road);
- foreach (var item in TargetRoad)
- {
- System.Diagnostics.Trace.WriteLine(item);
- }
- foreach (var item in PassedRoad)
- {
- System.Diagnostics.Trace.WriteLine(item);
- }
- }
- static void TraceBack(string CurrentRoad="", int NextStep = 0)
- {
- int Index = 0;
- if (NextStep > 0)
- {
- Index = NextStep;
- }
- for (; Index < InputArray.Count(); Index++)
- {
- int num = 0;
- if (!string.IsNullOrEmpty(CurrentRoad) && !CurrentRoad.Contains(","))
- {
- num = int.Parse(CurrentRoad);
- }
- if (CurrentRoad.Contains(","))
- {
- string[] array = CurrentRoad.Split(new char[] { ',' });
- foreach (var item in array)
- {
- num += int.Parse(item);
- }
- }
- if (InputArray[Index] + num == 20)
- {
- string TempStrNum = string.Empty;
- if (string.IsNullOrEmpty(CurrentRoad))
- {
- TempStrNum = InputArray[Index].ToString();
- }
- else
- {
- TempStrNum = CurrentRoad + "," + InputArray[Index].ToString();
- }
- if (!TargetRoad.Exists(a => a.Equals(TempStrNum)))
- {
- TargetRoad.Add(TempStrNum);
- if (CurrentRoad.Contains(","))
- {
- CurrentRoad = CurrentRoad.Remove(CurrentRoad.LastIndexOf(','));
- }
- else
- {
- CurrentRoad = string.Empty;
- }
- }
- break;
- }
- if (InputArray[Index] + num > 20)
- {
- if (CurrentRoad.Contains(","))
- {
- CurrentRoad = CurrentRoad.Remove(CurrentRoad.LastIndexOf(','));
- }
- else
- {
- CurrentRoad = string.Empty;
- }
- break;
- }
- if (InputArray[Index] + num < 20)
- {
- string TempValue = string.IsNullOrEmpty(CurrentRoad) ? InputArray[Index].ToString() : CurrentRoad + "," + InputArray[Index].ToString();
- if (!PassedRoad.Exists(a => a.Equals(TempValue)))
- {
- CurrentRoad = TempValue;
- PassedRoad.Add(CurrentRoad);
- TraceBack(CurrentRoad, Index + 1);
- }
- else
- {
- break;
- }
- }
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/1301201614418.html
来源: http://www.codesnippet.cn/detail/1301201614418.html