void Main() { var r = A(new List<string>(){"a","b","c","d","e","f"}); Console.WriteLine(r.Count); Console.WriteLine(r); } //1. loop each element //2. take out first,2nd... element //3. if after_take_out.Length > 1 then recursive //4. get child result then combine into new result static List<string> A(List<string> arr){ if(arr.Count <= 1){ return arr; } if(arr.Count == 2){ return new List<string>(){arr[0]+","+arr[1],arr[1]+","+arr[0]}; } var ret = new List<string>(); for(var i = 0;i < arr.Count;i ++){ var tmp = new List<string>(arr); var takeOut = arr[i]; arr.RemoveAt(i); if(arr.Count > 1){ var childR = A(arr); var r = GetResult(takeOut, childR); ret.AddRange(r); } } return ret; } //e.g GetResult("a",["b,c","c,b"]) //[a,b,c] //[b,a,c] //[b,c,a] //[a,c,b] //[c,a,b] //[c,b,a] static List<string> GetResult(string val, List<string> oldResult){ var ret = new List<string>(); for(var i = 0;i < oldResult.Count; i++){ var r = GetResult(val, oldResult[i]); foreach(var str in r){ ret.Add(str); } } return ret; } //e.g. GetResult("a", "b,c,d") //[a,b,c,d] //[b,a,c,d] //[b,c,a,d] //[b,c,d,a] static List<string> GetResult(string val, string old){ var newRet = new List<string>(); var arr = old.Split(‘,‘); for(var i = 0;i <= arr.Length ; i++){ var tmp = new List<string>(arr); tmp.Insert(i,val); newRet.Add(string.Join(",",tmp)); } return newRet; }
时间: 2024-10-05 05:05:06