【发布时间】:2016-07-29 22:20:26
【问题描述】:
如果我要使用交换和置换方法来生成排列,我知道如何处理重复问题,如 here 所示。
但是,我使用了一种不同的方法,在没有当前字符的情况下生成的所有排列中,我将当前字符放在任意两个字符的开头和结尾。 p>
如何修改下面的代码,以便在包含重复项的字符串中只给我唯一的排列
import java.util.ArrayList;
public class Permutations {
public static void main(String[] args) {
String str = "baab";
System.out.println(fun(str, 0));
System.out.println("number of Permutations =="+fun(str, 0).size());
}
static ArrayList<String> fun(String str, int index)
{
if(index == str.length())
{
ArrayList<String> al = new ArrayList<String>();
al.add("");
return al;
}
/* get return from lower frame */
ArrayList<String> rec = fun(str, index+1);
/* get character here */
char c = str.charAt(index);
/* to each of the returned Strings in ArrayList, add str.charAt(j) */
ArrayList<String> ret = new ArrayList<String>();
for(int i = 0;i<rec.size();i++)
{
String here = rec.get(i);
ret.add(c + here);
for(int j = 0;j<here.length();j++)
ret.add(here.substring(0,j+1) + c + here.substring(j+1,here.length()));
}
return ret;
}
}
此时,“bab”等字符串生成如下输出,其中多次包含abb和bba。
[bab, abb, abb, bba, bba, bab]
number of Permutations ==6
PS : 我不想使用 hashmap/Set 来跟踪我的重复项并查看它们之前是否遇到过。
【问题讨论】:
-
这不是 Codechef 的问题吗?
-
@VaibhavBajaj,嗨。正如我所说,我知道解决问题的解决方案,我正在寻找针对此特定实现的修改。
标签: java algorithm recursion permutation dynamic-programming