|
| 1 | +# -*-coding:utf-8 |
| 2 | +import copy |
| 3 | + |
| 4 | + |
| 5 | +def FindC(data, n, findedList, s, finded, curS): |
| 6 | + """ |
| 7 | + 从data数组中找出n个数使其和为s,可能的数组组合可能不止一个 |
| 8 | +
|
| 9 | + :param data: 数组,必须需要从小到大排过序 |
| 10 | + :param n: 一共找n个元素 |
| 11 | + :param findedList:item是finded,记录所有的可能的组合 |
| 12 | + :param s:和为s |
| 13 | + :param finded: 当前可能数组组合中元素对应的下标 |
| 14 | + :param curS:当前finded元素中的和,用它记录起来就不用每次都计算sum(finded)的值了 |
| 15 | +
|
| 16 | + """ |
| 17 | + if n == 0: |
| 18 | + return |
| 19 | + # 开始下标,如果finded中有元素就应该是finded的最后一个元素 |
| 20 | + startIndex = 0 |
| 21 | + if len(finded) != 0: |
| 22 | + startIndex = finded[-1] + 1 |
| 23 | + # 从startIndex向后遍历data |
| 24 | + for i in range(startIndex, m): |
| 25 | + # 假设data[i]是组合中的一个数 |
| 26 | + curS += data[i] |
| 27 | + # 如果加上data[i]之后curS的值还是小于s |
| 28 | + if curS < s: |
| 29 | + # 先将i加入finded |
| 30 | + finded.append(i) |
| 31 | + # 利用递归从data中找下一个元素 |
| 32 | + FindC(data, n, findedList, s, finded, curS) |
| 33 | + # 回溯,消除刚才的i,因为i不一定是最终组合的数,消除其影响后方便下一次遍历 |
| 34 | + curS -= data[i] |
| 35 | + del finded[-1] |
| 36 | + # 如果curS等于s而且元素数列为n-1(因为finded中没append i,所以只用等于n-1即可) |
| 37 | + elif curS == s and len(finded) == n - 1: |
| 38 | + findedValue = [] |
| 39 | + for itemFinded in finded: |
| 40 | + findedValue.append(data[itemFinded]) |
| 41 | + findedValue.append(data[i]) |
| 42 | + findedList.append(findedValue) |
| 43 | + break |
| 44 | + else: |
| 45 | + break |
| 46 | + |
| 47 | + |
| 48 | +def quickSort(data, low, high): |
| 49 | + if low>=high: |
| 50 | + return |
| 51 | + centerIndex = partation(data, low, high) |
| 52 | + quickSort(data, low, centerIndex - 1) |
| 53 | + quickSort(data, centerIndex + 1, high) |
| 54 | + |
| 55 | + |
| 56 | +def partation(data, low, high): |
| 57 | + curValue = data[low] |
| 58 | + while low < high: |
| 59 | + while low < high and data[high] >= curValue: |
| 60 | + high -= 1 |
| 61 | + |
| 62 | + t = data[low] |
| 63 | + data[low] = data[high] |
| 64 | + data[high] = t |
| 65 | + |
| 66 | + while low < high and data[low] <= curValue: |
| 67 | + low += 1 |
| 68 | + |
| 69 | + t = data[low] |
| 70 | + data[low] = data[high] |
| 71 | + data[high] = t |
| 72 | + |
| 73 | + return low |
| 74 | + |
| 75 | + |
| 76 | +data = [4, 2, 1, 4, 6, 3] |
| 77 | +quickSort(data,0,len(data)-1) |
| 78 | +print data |
| 79 | +# findedList = [] |
| 80 | +# finded = [] |
| 81 | +# curS = 0 |
| 82 | +# m = 6 |
| 83 | +# s = 12 |
| 84 | +# n = 4 |
| 85 | +# FindC(data, n, findedList, s, finded, curS) |
| 86 | +# print findedList |
0 commit comments