67,513
社区成员
发帖
与我相关
我的任务
分享
class Solution:
def __init__(self):
self.nums = None
self.len_nums = 0
self.total = 0
self.combinations = [ ]
def doGetlCombination(self, prefix, prefix_total, start):
if start >= self.len_nums:
return
num = self.nums[start]
if prefix_total + num == self.total:
new_prefix = prefix[:]
new_prefix.append(num)
self.combinations.append(new_prefix)
if prefix_total + num <= self.total:
new_prefix = prefix[:]
new_prefix.append(num)
self.doGetlCombination(new_prefix, prefix_total + num, start + 1)
self.doGetlCombination(prefix, prefix_total, start + 1)
def getAllCombination(self, nums, total):
self.nums = nums
self.len_nums = len(self.nums)
if 0 == self.len_nums:
return [ ]
self.total = total
self.doGetlCombination([ ], 0, 0)
return self.combinations
def main():
nums = [1, 2, 3, 4, 5, 6, -1, 1]
total = 10
solu = Solution()
print solu.getAllCombination(nums, total)
int[] a = {1,2,3,4,5,6};
int b = 10;
for (int i=0;i<1<<a.length;i++){
int sum = 0;
String s = "";
for (int j=0;j<a.length;j++){
if ((i>>j&1)==1){
sum += a[j];
s += a[j]+" ";
}
}
if (sum==b){
System.out.println(s);
}
}