알고리즘 연습 - C \ # DFS 전체 배열 알고리즘

void Main()
{
	var r = A(new List(){"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 A(List arr){
if(arr.Count <= 1){
return arr;
}

if(arr.Count == 2){
return new List(){arr[0]+","+arr[1],arr[1]+","+arr[0]};
}

var ret = new List();
for(var i = 0;i < arr.Count;i ++){
var tmp = new List(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 GetResult(string val, List oldResult){

var ret = new List();
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 GetResult(string val, string old){

var newRet = new List();

var arr = old.Split(',');
for(var i = 0;i <= arr.Length ; i++){
var tmp = new List(arr);
tmp.Insert(i,val);
newRet.Add(string.Join(",",tmp));
}

return newRet;
}

좋은 웹페이지 즐겨찾기