• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
frogking
Happy and Health

导航

  • 博客园
  • 首页
  • 新随笔
  • 联系
  • 订阅 订阅
  • 管理

公告
 

组合问题 递归回溯解法

1,

Given  two integers n and k, return all possible combinations of k numbers out of 1 … n. You may return the answer in any order.

Example 1:
Input: n = 4, k = 2
Output:

1
2
3
4
5
6
7
8
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Example 2:
Input: n = 1, k = 1
Output: [[1]]

  Teaching Kids Programming – Recursive Backtracking Algorithm to Compute the Combinations | Algorithms, Blockchain and Cloud (helloacm.com)

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def dfs(left, cur):
            if len(cur) == k:   # finish k items
                output.append(cur[:])
                return
            for i in range(left, n + 1):
                cur.append(i)   # pick i
                dfs(i + 1, cur) # pick next from i+1
                cur.pop()       # reset for next iteration
        output = []
        dfs(1, [])
        return output            

发现没有,组合算法中,传入的开始位置是i,里面循环开始是i+2. 这时关键,因为组合不考虑顺序问题,比如【1,3】组合有后,3开始的组合就不用考虑【3,1】了。

那是不是在做全排列时,改这个i+1从还是从第一个值开始即可?

 

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def dfs(left, ans):
            if left == len(nums):
                ans.append(deepcopy(nums))
                return
            for i in range(left, len(nums)):
                nums[i], nums[left] = nums[left], nums[i]
                dfs(left + 1, ans)
                nums[i], nums[left] = nums[left], nums[i]
        ans = []
        dfs(0, ans)
        return ans

 

Teaching Kids Programming – Recursive Permutation Algorithm | Algorithms, Blockchain and Cloud (helloacm.com)

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2:
Input: nums = [0,1]
Output: [[0,1],[1,0]]

Example 3:
Input: nums = [1]
Output: [[1]]

Constraints:
1 <= nums.length <= 6
-10 <= nums[i] <= 10
All the integers of nums are unique.

posted on 2022-07-25 11:16  frogking  阅读(36)  评论(0)    收藏  举报
 
刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3