程式設計實踐筆記No.6
阿新 • • 發佈:2021-01-18
技術標籤:程式設計實踐
程式設計實踐筆記No.6
寫在最前面,程式設計一直是我的短板,希望在leetcode練習中獲得進步!
參考Datawhale組隊學習中“LeetCodeTencent”
題目一43. 字串相乘
合併 k 個排序連結串列,返回合併後的排序連結串列。請分析和描述演算法的複雜度
程式碼
# 怪不得不用python
class Solution:
def multiply(self, num1: str, num2: str) -> str:
anws = int(num1)*int(num2)
return str(anws)
題目二 46. 全排列
給定一個 沒有重複 數字的序列,返回其所有可能的全排列。。
思路
回溯法(back tracking) 是一種選優搜尋法,又稱為試探法,按選優條件向前搜尋,以達到目標。但當探索到某一步時,發現原先選擇並不優或達不到目標,就退回一步重新選擇,這種走不通就退回再走的技術為回溯法,而滿足回溯條件的某個狀態的點稱為“回溯點”。
程式碼
public class Solution { private IList<IList<int>> _result; private bool[] _used; public IList<IList<int>> Permute(int[] nums) { _result = new List<IList<int>>(); if (nums == null || nums.Length == 0) return _result; _used = new bool[nums.Length]; FindPath(nums, 0, new List<int>()); return _result; } public void FindPath(int[] nums, int count, List<int> path) { if (count == nums.Length) { //遞迴終止條件 List<int> item = new List<int>(); item.AddRange(path); //加入拷貝 _result.Add(item); return; } for (int i = 0; i < nums.Length; i++) { if (_used[i] == false) { path.Add(nums[i]); _used[i] = true; FindPath(nums, count + 1, path); path.RemoveAt(path.Count - 1); _used[i] = false; } } } }
題目三 33. 搜尋旋轉排序陣列
給定一個整數陣列 nums,找到一個具有最大和的連續子陣列(子陣列最少包含一個元素),返回其最大和。
程式碼
public class Solution { public int MaxSubArray(int[] nums) { int len = nums.Length; if (len == 0) return 0; if (len == 1) return nums[0]; int[] max = new int[len]; max[0] = nums[0]; int result = max[0]; for (int i = 1; i < len; i++) { if (max[i - 1] + nums[i] > nums[i]) { max[i] = max[i - 1] + nums[i]; } else { max[i] = nums[i]; } if (max[i] > result) { result = max[i]; } } return result; } }