Java 生成序列
我正在寻找关于以下问题的解释 给定一个整数的输入数组,比如1234,我想产生所有可能的排列,看起来像这样01,02,第一个像这样一直到04,下一个看起来像是0 0 1 0,然后是0 0 1 1。我希望你明白我的意思。我已经构建了一个迭代算法来生成序列,但是它对大小为10的输入使用了太多内存,我正在寻找的解决方案不使用递归。请注意有n+1!0,0,0,0包括可能性 输入仅限于整数,并且生成的值的计数始终等于输入值的计数 编辑 请注意,Stackoverflow中可能有这样一个解决方案,但我不能真正为这个问题定义一个合适的名称,这就是为什么如果任何人对如何实际命名这个问题有任何线索,请分享!Java 生成序列,java,c#,.net,algorithm,permutation,Java,C#,.net,Algorithm,Permutation,我正在寻找关于以下问题的解释 给定一个整数的输入数组,比如1234,我想产生所有可能的排列,看起来像这样01,02,第一个像这样一直到04,下一个看起来像是0 0 1 0,然后是0 0 1 1。我希望你明白我的意思。我已经构建了一个迭代算法来生成序列,但是它对大小为10的输入使用了太多内存,我正在寻找的解决方案不使用递归。请注意有n+1!0,0,0,0包括可能性 输入仅限于整数,并且生成的值的计数始终等于输入值的计数 编辑 请注意,Stackoverflow中可能有这样一个解决方案,但我不能真正
谢谢 考虑使用以避免存储每个生成的值。要生成序列,基本上要执行以下操作: 从只包含正确长度的零的数组开始 迭代,每次迭代都要做一些基本的数学运算,比如递增数字,就好像数组中的每个元素都是一个较大数字的一位数。 基本上将最后一个数字增加1 如果最终高于该位置的最大值,请将其重置为0,然后移到左边的数字 如果最终没有超过最大值,您将得到一个新的解决方案 当移到左边的数字操作从数组的左端脱落时,就完成了 以下是一个解决方案,它演示了:
void Main()
{
CountedPermutations(1, 2, 3)
.Select(l => new { a = l[0], b = l[1], c = l[2] })
.Dump();
}
public static IEnumerable<int[]> CountedPermutations(params int[] maxValues)
{
int[] results = new int[maxValues.Length];
yield return results; // the all-zeroes solution
while (true)
{
// Increment to next solution
if (CountedPermutationsMutate(results, maxValues))
{
// make a copy of the array and yield return it
// we make copies so that if the outside code puts everything in a
// collection, we don't just end up with N references to the same array
// with the same values.
yield return results.ToArray();
}
else
break;
}
}
public static bool CountedPermutationsMutate(int[] values, int[] maxValues)
{
int index = values.Length - 1;
bool gotSolution;
while (true)
{
if (values[index] < maxValues[index])
{
// won't overflow this position, so we got a new solution
values[index]++;
gotSolution = true;
break;
}
else
{
// Overflow in this position, reset to 0
// and move on to the next digit to the left
values[index] = 0;
index--;
// If we fell off the left end of the array, we're done
if (index < 0)
{
gotSolution = false;
break;
}
}
}
return gotSolution;
}
我更关心的是创建置换的算法。它确实需要一个动态创建的循环,这样递归就可以提供。我肯定会使用yield-return语句。
0 0 0
0 0 1
0 0 2
0 0 3
0 1 0
0 1 1
0 1 2
0 1 3
0 2 0
0 2 1
0 2 2
0 2 3
1 0 0
1 0 1
1 0 2
1 0 3
1 1 0
1 1 1
1 1 2
1 1 3
1 2 0
1 2 1
1 2 2
1 2 3