我希望能够获取一个数字的所有组合,且没有重复。 像0.1.2、0.2.1、1.2.0、1.0.2、2.0.1、2.1.0这样。 我试图找到一个简单的方法,但是失败了。我画了一张图/树来解决它,这正呼唤着使用递归。 但如果可能的话,我想不用递归来做这个。
请问有人可以帮我吗?
我希望能够获取一个数字的所有组合,且没有重复。 像0.1.2、0.2.1、1.2.0、1.0.2、2.0.1、2.1.0这样。 我试图找到一个简单的方法,但是失败了。我画了一张图/树来解决它,这正呼唤着使用递归。 但如果可能的话,我想不用递归来做这个。
请问有人可以帮我吗?
@Filip Nyugen提供的解决方案是针对那些想要使用JS获得答案的人。
function printPermutationsIterative(string) {
const factorials = [];
factorials[0] = 1;
for (let i = 1; i <= string.length; i++) {
factorials[i] = factorials[i - 1] * i;
}
for (let i = 0; i < factorials[string.length]; i++) {
let onePermutation = "";
let temp = string;
let positionCode = i;
for (let position = string.length; position > 0; position--) {
let selected = positionCode / factorials[position - 1];
onePermutation += temp.charAt(selected);
positionCode = positionCode % factorials[position - 1];
temp = temp.substring(0, selected) + temp.substring(selected + 1);
}
console.log(onePermutation);
}
}
import java.util.LinkedList;
import java.util.List;
public class Permutations {
public void perm(String input) {
List<String[]> buffer = new LinkedList<>();
buffer.add(new String[]{input, ""});
while (!buffer.isEmpty()) {
String[] perm = buffer.remove(0);
System.out.println(perm[1]);
for (int i = 0; i < perm[0].length(); i++) {
buffer.add(new String[]{perm[0].substring(0, i) + perm[0].substring(i + 1), perm[1] + perm[0].charAt(i)});
}
}
}
}
import java.io.*;
class Permutation
{
String w;
public void accept() throws IOException
{ BufferedReader ak=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a word"); w=ak.readLine(); }
public void permute()
{
int l,s,m,p,k,t,x,n,r;
s=m=0;p=t=k=1;
l=w.length();
for(x=1;x<=l;x++)
{
p*=x; s+=x; t*=10;
}
System.out.println("\n"+"The "+p+" possible permutations of the word are:"+"\n");
for(x=t/10;x
public boolean isUnique(int n) {
int a[]={0,0,0,0,0,0,0,0,0,0};
int r;
while(n!=0)
{
r=n%10;
if(a[r]!=0 || r==0)
return false;
else
a[r]++;
n/=10;
}
return true;
}
}