比如 用 a,b,c,d 4个字符组成一个8个长度的字符串,问一共有多少可能,应该有4的8次方种,用代码简单实现
private string[] AAA() { string[] cs = { "a", "b", "c", "d" }; string[] ts = new string[8]; string[] ss = new string[Convert.ToInt32(Math.Pow(cs.Length, 8))]; int index = 0; for (int i_0 = 0; i_0 < cs.Length; i_0++) { for (int i_1 = 0; i_1 < cs.Length; i_1++) { for (int i_2 = 0; i_2 < cs.Length; i_2++) { for (int i_3 = 0; i_3 < cs.Length; i_3++) { for (int i_4 = 0; i_4 < cs.Length; i_4++) { for (int i_5 = 0; i_5 < cs.Length; i_5++) { for (int i_6 = 0; i_6 < cs.Length; i_6++) { for (int i_7 = 0; i_7 < cs.Length; i_7++) { ts[0] = cs[i_0]; ts[1] = cs[i_1]; ts[2] = cs[i_2]; ts[3] = cs[i_3]; ts[4] = cs[i_4]; ts[5] = cs[i_5]; ts[6] = cs[i_6]; ts[7] = cs[i_7]; ss[index++] = String.Join("-", ts); } } } } } } } } return ss; }
上面的代码显然还是可以优化的
private string[] BBB() { string[] cs = { "a", "b", "c", "d" }; int power = 8; string[] ss = new string[Convert.ToInt32(Math.Pow(cs.Length, power))]; string[] ts = new string[power]; int i = 0; int index = 0; Recur(cs, ref i, power - 1, ts, ref index, ss); return ss; } private void Recur(string[] cs, ref int i, int power, string[] ts, ref int index, string[] ss) { for (int j = 0; j < cs.Length; j++) { ts[i] = cs[j]; if (i < power) { i++; Recur(cs, ref i, power, ts, ref index, ss); } else { ss[index++] = String.Join("-", ts); } } i--; }