对于以下问题,我将不胜感激。我有从 0 到 n-1 的 n 个整数,我正在尝试生成长度为 k 的所有可能组合的列表(即 k 个连接整数),这样每对连续整数都不相等。因此,例如,(1)(2)(3)(2) 在 k = 4 时有效,但 (1)(2)(3)(3) 无效。关于如何最有效地解决这个问题的任何想法?(我不太关心代码的长度/复杂程度,只关心效率)
anon
问问题
2830 次
3 回答
3
这是代码:
void Generate(int[] source, List<int[]> result, int[] build, int k, int num) {
if (num == k) {
int[] a = (int[])build.clone();
result.add(a);
return;
}
for (int i = 0; i < source.length; i++)
if (num == 0 || source[i] != build[num - 1])
{
build[num] = source[i];
Generate(source, result, build, k, num + 1);
}
}
如何调用:
int k = 2;
List<int[]> a = new ArrayList<int[]>();
Generate(new int[]{1,2,3}, a, new int[k], k, 0);
于 2012-04-28T19:17:35.497 回答
0
public static void recursiveOutput(Integer n, int k, int limit, String prints){
k++;
if(k>limit)
return;
String statePrints = prints;
//cycle through all available numbers
for(Integer i = 1; i<=n; i++)
{
statePrints = prints;
//First cycle
if(k==1){
statePrints+= "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
//check if predecessor is not the same
if(i != Integer.parseInt(statePrints.substring(statePrints.length()-2,statePrints.length()-1))){
statePrints += "(" + i.toString() + ")";
recursiveOutput(n, k, limit, statePrints);
}
}
//Check if the length matches the combination length
if(statePrints.length() == 3 * limit)
System.out.println(statePrints);
}
称呼 :recursiveOutput(3,0,4,"");
于 2012-04-28T19:22:04.160 回答
0
public class Generator {
final int k = 2;
final char[] n = new char[]{'0','1','2','3','4','5','6','7','8','9'};
final char[] text = new char[k];
public void gen(int i, int not_n) {
if(i == k) {
System.out.println(text);
return;
}
for(int j = 0; j < n.length; j++) {
if(j == not_n) continue;
text[i] = n[j];
gen(i+1, j);
}
}
public static void main(String[] args) {
new Generator().gen(0, -1);
}
}
于 2012-04-28T19:28:36.957 回答