我怎样才能得到一个句子中单词的所有排列。你能给出一个示例 C# 代码吗? 例如:如果句子是“C# not java”, 输出应该是,1)c# not java 2)c# java not 3)java not c# 4)java c# not 5)not java c# 6)not c# java 等等
最佳答案
尝试一下这是否适合您。
public static List<string> PermuteWords(string s)
{
string[] ss = s.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);
bool[] used = new bool[ss.Length];
string res = "";
List<string> list = new List<string>();
permute(ss, used, res, 0, list);
return list;
}
private static void permute(string[] ss, bool[] used, string res, int level, List<string> list)
{
if (level == ss.Length && res != "")
{
list.Add(res);
return;
}
for (int i = 0; i < ss.Length; i++)
{
if (used[i]) continue;
used[i] = true;
permute(ss, used, res + " " + ss[i], level + 1, list);
used[i] = false;
}
}
关于c# - 找到句子中单词的所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2635868/