Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]
1 #简单版本
2 def Two_Sum(nums,target):
3 i = 0
4 j = 1
5 while i < len (nums):
6 while j < len(nums):
7 if nums[i] + nums[j] == target:
8 print (i, j)
9 break
10 j += 1
11 i += 1
12
13 nums = [2,7,11,15]
14 target = int(input("输入target:"))
1 #复杂版本--修改:已知n个不同整数wi的集合,求该集合的所有满足条件的子集,使得每个子集的正数之和等于另一个给定的正数M
2 #回溯法解决子集和数问题
3 #两种形式:1.固定长度n-元组
4 #2.可变元组
5 def SumOfSum(s,k,r,x,M,w):
6 x[k] = 1
7 if s + w[k] == M:
8 print(x)
9 elif s + w[k] + w[k+1] <= M:#搜索左子树
10 SumOfSum(s+w[k],k+1,r-w[k],x,M,w)
11 elif s + r - w[k] >= M and s + w[k+1] <= M:#搜索右子树
12 x[k] = 0
13 SumOfSum(s,k+1,r-w[k],x,M,w)
14
15 def SumOfSum1(x,M,w):
16 r = 0
17 for i in range(len(w)):
18 r = r + w[i]
19 print(r)#73
20 if r >= M and w[0] <= M:
21 SumOfSum(0,0,r,x,M,w)
22
23 n = 6
24 x = [0] * 6
25 w = [5, 10, 12, 13, 15, 18]
26 M = 30
27 SumOfSum1 (x, M, w)