我参加了一个竞赛,问题是要从N个项目的数组中找出有效数字的K个数字。
例如
3 -> N (Number of items in Array)
1 2 3 ->A (The array itself constituting N items)
2 -> K (This is the given number of digits to form)
[0,1] = 12
[0,2] = 13
[1,0] = 21
[1,2] = 23
[2,0] = 31
[2,1] = 32
我猜dynamic problem
可以解决此问题的逻辑是什么,但如果能得到帮助,我将感到非常高兴。
答案 0 :(得分:2)
我们可以构造一个递归函数,该函数可以从给定的一位整数整数数组中打印出所有可能的K位数字。 Ideone链接:https://ideone.com/RTNz2o
def gen(A, K, arr = []):
if len(arr) == K:
print (arr, "=", "".join([str(A[i]) for i in arr]))
for i in range(0, len(A)):
val = A[i]
if val == 0 and len(arr) == 0:
# We don't want numbers starting with 0
continue
if i in arr:
# We don't want to include the same element again
continue
arr.append(i)
gen(A, K, arr)
arr.pop()
gen([1, 2, 3], 2)