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]]
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
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.