[英]The possible combinations of n digits
我想編寫一個 C 函數,它以一個整數作為輸入,並使用這么多數字為我提供所有可能的組合。
例如:
cases(3);
輸出:
123 132 213 231 312 321
它使用前三位數字來創建一個三位數字,請注意,我需要它來處理任意數量的數字 n。
注意 case(3) 有 3 個! = 6 個結果。 所以 case(4) 有 4 個! = 24 個結果等等。
實際上,我什至不知道如何解決這個問題,因此感謝任何幫助。
獲勝的遞歸:-)
1
N
數字的組合是N - 1
數字的遞歸組合,在每個可能的地方添加N
在實際嘗試編寫代碼之前,請嘗試考慮算法。 想想當你寫下你想要的輸出時,你是如何在頭腦中解決這個問題的。 只需找到一種系統的方法來執行此操作:例如,您從最小的數字開始,然后檢查其他數字......
我已經在python中編寫了邏輯和代碼
#n digit number as input converted into list
m=int(input("enter number of digits:"))
f=[]
for i in range(1,m+1):
f.append(str(i))
#dynamic array for dynamic for loop inside recursion
a=[0 for k in range(len(f))]
c=[]#list which is to be used for append for digits
ans=[]# result in which the
# recursion for if loop inside for loop
#1st argument is fixed inside the loop
#2nd argument will be decreasing
def conditn(k,m):
if(m==0):
return 1
if(m==1):
if(a[k]!=a[0]):
return 1
if(a[k]!=a[m-1] and conditn(k,m-1)):
return 1
#recursion for for loop
#1st argument y is the length of the number
#2nd argument is for initialization for the varible to be used in for loop
#3rd argument is passing the list c
def loop(y, n,c):
if n<y-1:
#recursion until just befor the last for loop
for a[n] in range(y):
if(conditn(n,n)):
loop(y, n + 1,c)
else:
# last for loop
if(n==y-1):
for a[n] in range(y):
#last recursion of condition
if(conditn(n,n)):
#concatinating the individual number
concat=""
for i in range(y):
concat+=f[a[i]]+""
c.append(concat)
#returning the list of result for n digit number
return c
#printing the list of numbers after method call which has recursion within
#set is used used to convert any of the iterable to the
#distinct element and sorted sequence of iterable elements,
for j in (loop(len(f),0,c)):
print(j)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.