数据结构算法刷题(学习笔记二)

数据结构和算法

1.算法时间复杂度

  • 一般情况下,随着输入规模n的增大,T(n)增长的最慢的算法我们称之为最优算法。
  • 常数阶、线性阶、平方阶、对数阶

2.函数调用的时间复杂度分析

  • 常用的时间复杂度所消耗的时间从大到小的依次顺序是:O(1) < O(logn) < n < O(nlogn) < O(n^2) < O(n^3) < O(n!) < O(n^n)

3.算法的空间复杂度
4.线性表

每日一题

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]

-2
-3
-3
-2
-2
-6
-7
-2
-3
-3
-2
-2
7
5
4
1
2
0
1
0
3
2
0
0
1
  • 第一时间想到减法:减下来结果为零的话,则输出结果因为减数的集合(如何除去重复的部分 如:[2,2,3]、[2,3,2]、[3,2,2])
  • 目前整体想法为:先从小到大排序(.sort()),留下<=目标数的数列 所需数列一定在其中 利用回溯法 进行循环 得出最终结果

问题:

  • 1、.sort()方法是在原地对列表排序,是对原列表的直接操作,并不会返回一个新的列表。sort()方法需要单独使用,如果和赋值,打印等方法一起使用,结果会返回None
  • 2、del 删除的是变量,而不是数据。 del my_list[j:] 位置索引

代码如下:

candidates = [2, 3, 5]
target = 8
# 对初始列表进行简化处理
candidates.sort()
res = []  # 记录结果


# 删除函数
def candidates_del(x, y):
    j = 0
    for i in x:
        j = j + 1
        if i >= y:
            del x[j:]
            break


candidates_del(candidates, target)

# print(candidates)
# 完成简化初始数组

# 选取出列表中最小的作为判断值t
t = min(candidates)
n = len(candidates)


# print(t)

def backtrace(rs_candidates, rs_target, curr_res, s):
    # 跳出条件
    if rs_target == 0:
        res.append(curr_res[:])
        # print('成功路线')
        # print(res)
        return
    elif rs_target < t:
        # print('失败路线')
        return
    for i in range(s, n):
        # print(rs_target)
        curr_res.append(rs_candidates[i])
        # print(curr_res)
        # 删除
        # 开始回溯
        backtrace(rs_candidates, rs_target - rs_candidates[i], curr_res, i)
        curr_res.pop()


# print(candidates)
backtrace(candidates, target, [], 0)
print(res)

cc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值