python_lintcode_730. 所有子集的和_720. Rearrange a String With Integers

本文介绍了解决两个算法问题的方法:一是求解整数集合所有子集的元素和,二是重新排列包含字母和数字的字符串,使字母按字典序排列并附加数字之和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路

1: 1
   2
频次:1:1个=2^(1-1)
      2:12: 1
   2
   1,2
频次:1:2个=2^(2-1)
      2:23:  1
    2
    3
    1,2
    1,3
    2,3
    1,2,3
频次:1:4个=2^(3-1)
      2:43:44:  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:83:84: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).

思路

  • 题目解析:就是字母按着顺序排序,然后所有的数字相加放在最后,且最后是以字符串形式输出。
    1. 字符串转成列表,然后sort()顺序排序,数字会在前面,为a
    2. 判断最后一个数字的index,并把前面所有的数字相加,为num
    3. 取a中index后面的所有字母,并append()尾巴添加num
    4. 将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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值