110,547
社区成员
发帖
与我相关
我的任务
分享
private void Combining(string str,int count)
//str中没有重复字符,要求将str中的字符任意提取出count个进行组合。不用排列。str的长度大于等于count。
{
if(str.Length<count) return;
//这里的代码如何写?
}
namespace consoleapp
{
class Program
{
static void Main(string[] args)
{
var l = Combine("abcde", 4);
foreach (char[] ca in l)
{
Console.WriteLine(new string(ca));
};
Console.ReadLine();
}
private static List<char[]> Combine(string s,int count)
{
List<char[]> l = new List<char[]>();
if (count == 1)
{
foreach (char c in s)
{
char[] ca = new char[1];
ca[0] = c;
l.Add(ca);
};
}
else
{
for (int i = 0; i < s.Length; i++)
{
List<char[]> lsub;
if (s.Length - 1 >= count - 1)
{
lsub = Combine(s.Substring(i + 1), count - 1);
foreach (char[] a in lsub)
{
char[] ca = new char[count];
a.CopyTo(ca, 0);
ca[count - 1] = s[i];
l.Add(ca);
};
};
};
};
return l;
}
}
namespace WindowsApplication9
{
public partial class Form1 : Form
{
String Result = String.Empty;
int Count = 3;
public Form1()
{
String S = "ABCDEFGH";
String TempResult = String.Empty;
int TempCount = Count;
GetIt(S, Count, ref TempResult);
MessageBox.Show(Result);
}
void GetIt(String S, int TempCount, ref String TempResult)
{
if (TempCount == 0)
{
String[] Results=Result.Split(' ');
for (int i = 0; i < Results.Length; i++)
{
bool IsHad = true;
for (int j = 0; j < Count; j++)
IsHad = IsHad && Results[i].IndexOf(TempResult[j]) >= 0;
if (IsHad)
return;
}
Result += TempResult + " ";
return;
}
for (int i = 0; i < S.Length; i++)
{
String C = S.Substring(i, 1);
String T = S.Remove(i, 1);
TempResult += C;
GetIt(T, TempCount - 1, ref TempResult);
TempResult = TempResult.Remove(TempResult.Length - 1, 1);
}
}
}
}
namespace WindowsApplication9
{
public partial class Form1 : Form
{
String Result = String.Empty;
public Form1()
{
String S = "ABCDEFGH";
int Count = 3;
String TempResult = String.Empty;
GetIt(S, Count, ref TempResult);
MessageBox.Show(Result);
}
void GetIt(String S, int Count, ref String TempResult)
{
if (Count == 0)
{
Result += TempResult + " ";
return;
}
for (int i = 0; i < S.Length; i++)
{
String C = S.Substring(i, 1);
String T = S.Remove(i, 1);
TempResult += C;
GetIt(T, Count - 1, ref TempResult);
TempResult = TempResult.Remove(TempResult.Length - 1, 1);
}
}
}
}
class Program
{
static void Main(string[] args)
{
Combining("58fgj6nsz",5);
}
static void Combining(string str, int count)
//str中没有重复字符,要求将str中的字符任意提取出count个进行组合。不用排列。str的长度大于等于count。
{
string res = "";
if (str.Length < count) return;
Random r = new Random();
while (res.Length != count)
{
string t = str[r.Next(str.Length)].ToString();
if (!res.Contains(t.ToString()))
res += t;
}
Console.WriteLine(res);
}
}