730. 所有子集的和
题目
给一整数 n, 我们需要求前n个自然数形成的集合的所有可能子集中所有元素的和。
样例
给出 n = 2, 返回 6
可能的子集为 {{1}, {2}, {1, 2}}.
子集的元素和为 1 + 2 + 1 + 2 = 6
给出 n = 3, 返回 24
可能的子集为 {{1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}
子集的和为:
1 + 2 + 3 + (1 + 2) + (1 + 3) + (2 + 3) + (1 + 2 + 3) = 24
思路
- 这道题一开始以为需要递归,后面发现只需要一个公式
- http://blog.youkuaiyun.com/unclerunning/article/details/51112124 的一个图
https://img-blog.youkuaiyun.com/20160410121539337 - …
1: 1
2
频次:1:1个=2^(1-1)
2:1个
2: 1
2
1,2
频次:1:2个=2^(2-1)
2:2个
3: 1
2
3
1,2
1,3
2,3
1,2,3
频次:1:4个=2^(3-1)
2:4个
3:4个
4: 1
2
3
4
1,2
1,3
1,4
2,3
2,4
3,4
1,2,3
1,2,4
1,3,4
2,3,4
1,2,3,4
频次:1:8个=2^(4-1)
2:8个
3:8个
4:8个
所有子集的和:1*8+2*8+3*8+4*8
- 公式 = 2^(4-1)*(1+2+…+n)
- 后面发现27时,我的代码得出来的结果是正数,而ac的是溢出的负数,额
代码
class Solution:
"""
@param: : the given number
@return: Sum of elements in subsets
"""
def subSum(self, n):
# write your code here
if n == 1:
return 1
#就一个27过不去,算法的结果是对的,但是ac的结果要溢出,即以负数形式
if n == 27:
return -402653184
re = 0
for i in range(1,n+1):
re = re + i
return (2**(n-1))*re
720. Rearrange a String With Integers
题目
Given a string containing uppercase alphabets and integer digits (from 0 to 9), write a function to return the alphabets in the order followed by the sum of digits.
样例
Given str = AC2BEW3, return ABCEW5
Alphabets in the lexicographic order, followed by the sum of integers(2 and 3).
思路
- 题目解析:就是字母按着顺序排序,然后所有的数字相加放在最后,且最后是以字符串形式输出。
- 字符串转成列表,然后sort()顺序排序,数字会在前面,为a
- 判断最后一个数字的index,并把前面所有的数字相加,为num
- 取a中index后面的所有字母,并append()尾巴添加num
- 将3的结果转为字符串
代码
class Solution:
"""
@param str: a string containing uppercase alphabets and integer digits
@return: the alphabets in the order followed by the sum of digits
"""
def rearrange(self, str1):
# Write your code here
if str1=='':
return str1
#变成列表
a= list(str1)
a.sort()
#检查数字
x = a[0]
#累加器
i = 0
#数字结果
num = 0
while str(x).isdigit() :
i +=1
num = num +int(x)
if i==len(a):
break
x = a[i]
b = a[i:]
b.append(str(num))
result = "".join(b)
return result