Re: [閒聊] 每日leetcode已回收
看板Marginalman作者sustainer123 (caster )時間1年前 (2024/05/21 12:16)推噓1(1推 0噓 1→)留言2則, 2人參與討論串252/1554 (看更多)
※ 引述《ray90514 ()》之銘言:
: 78. Subsets
: 基本上跟昨天一樣 不過這次試著寫一個非遞迴的
: class Solution {
: public:
: vector<vector<int>> subsets(vector<int>& nums) {
: vector<vector<int>> ans;
: ans.push_back(vector<int>());
: for(int n : nums){
: int len = ans.size();
: for(int i = 0; i < len; i++){
: vector<int> v = ans[i];
: v.push_back(n);
: ans.push_back(v);
: }
: }
: return ans;
: }
: };
思路:
backtracking
Python Code:
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def backtrack(state,nums,start,res):
if state not in res:
res.append(list(state))
for i in range(start,len(nums)):
state.append(nums[i])
backtrack(state,nums,i+1,res)
state.pop()
res=[[]]
backtrack([],nums,0,res)
return res
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.130.118 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1716264967.A.21A.html
→
05/21 12:16,
1年前
, 1F
05/21 12:16, 1F
推
05/21 12:22,
1年前
, 2F
05/21 12:22, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 252 之 1554 篇):