thảo luận Leetcode mỗi ngày

Python:
class Solution:
    def beautifulSubsets(self, nums: List[int], k: int) -> int:
        def beautifulSubsetsOfArithmeticSequence(sequence):
            n = len(sequence)
            dp = n * [0]
            for i in range(n):
                prev2 = dp[i - 2] if i - 2 >= 0 else 1
                prev1 = dp[i - 1] if i - 1 >= 0 else 1
                take = ((1 << counter[sequence[i]]) - 1) * prev2
                notTake = prev1
                dp[i] = take + notTake
            return dp[n - 1]
        
        counter = Counter(nums)
        ans = 1
        for num in counter:
            if num - k not in counter: #num is the start of an arithmetic sequence
                sequence = []
                while num in counter:
                    sequence.append(num)
                    num += k
                ans *= beautifulSubsetsOfArithmeticSequence(sequence)
        return ans - 1 # "- 1" is to eliminate the empty set from the count
 
Python:
class Solution:
    def beautifulSubsets(self, nums: List[int], k: int) -> int:
        def beautifulSubsetsOfArithmeticSequence(sequence):
            n = len(sequence)
            dp = n * [0]
            for i in range(n):
                prev2 = dp[i - 2] if i - 2 >= 0 else 1
                prev1 = dp[i - 1] if i - 1 >= 0 else 1
                take = ((1 << counter[sequence[i]]) - 1) * prev2
                notTake = prev1
                dp[i] = take + notTake
            return dp[n - 1]
       
        counter = Counter(nums)
        ans = 1
        for num in counter:
            if num - k not in counter: #num is the start of an arithmetic sequence
                sequence = []
                while num in counter:
                    sequence.append(num)
                    num += k
                ans *= beautifulSubsetsOfArithmeticSequence(sequence)
        return ans - 1 # "- 1" is to eliminate the empty set from the count
nhìn có vẻ không O(n) lắm nhỉ :confused:
 
C++:
class Solution {
public:
    bool isBeauty(vector<int> &vIn, int num, int k)
    {
        for(auto &it: vIn) if(abs(it-num) == k) return false;
        return true;
    }
    void bt(vector<int>&vCur, vector<int>& nums, int idx, int k, int &re)
    {
        while(idx<nums.size())
        {
            if(isBeauty(vCur,nums[idx],k))
            {
                vCur.push_back(nums[idx]);
                ++re; ++idx;
                bt(vCur,nums,idx,k,re);
                vCur.pop_back();
            }
            else  ++idx;
        }
    }
    int beautifulSubsets(vector<int>& nums, int k) {
        int re = 0;
        vector<int> vCur;
        bt(vCur,nums,0,k,re);
        return re;
    }
};
 
Python:
class Solution:
    def beautifulSubsets(self, nums: List[int], k: int) -> int:
        
        def isBeautiful(arr, value):
            for el in arr:
                if abs(el - value) == k:
                    return False
            return True
        
        self.result = 0
        n = len(nums)
        def backtracking(i, arr):
            if i == n:
                return
            
            if isBeautiful(arr, nums[i]):
                self.result += 1
                arr.append(nums[i])
                backtracking(i + 1, arr)
                arr.pop()

            backtracking(i+1, arr)

        backtracking(0, [])     
        
        return self.result
 
nhìn có vẻ không O(n) lắm nhỉ :confused:
bác nhìn kỹ đi, có nested loop nhưng số lần visit qua từng phần tử là constant.
Ý tưởng là tách nums thành các dãy cấp số cộng dung sai k, rồi tính số beatiful subset từng dãy cấp số cộng bằng quy hoạch động. Để tách, mình sẽ duyệt qua từng số xem nó phải là số bắt đầu của một dãy cấp số cộng hay không.
 
Python:
class Solution:
    def beautifulSubsets(self, nums: List[int], k: int) -> int:
        def beautifulSubsetsOfArithmeticSequence(sequence):
            n = len(sequence)
            dp = n * [0]
            for i in range(n):
                prev2 = dp[i - 2] if i - 2 >= 0 else 1
                prev1 = dp[i - 1] if i - 1 >= 0 else 1
                take = ((1 << counter[sequence[i]]) - 1) * prev2
                notTake = prev1
                dp[i] = take + notTake
            return dp[n - 1]
       
        counter = Counter(nums)
        ans = 1
        for num in counter:
            if num - k not in counter: #num is the start of an arithmetic sequence
                sequence = []
                while num in counter:
                    sequence.append(num)
                    num += k
                ans *= beautifulSubsetsOfArithmeticSequence(sequence)
        return ans - 1 # "- 1" is to eliminate the empty set from the count
bác nhìn kỹ đi, có nested loop nhưng số lần visit qua từng phần tử là constant.
Ý tưởng là tách nums thành các dãy cấp số cộng dung sai k, rồi tính số beatiful subset từng dãy cấp số cộng bằng quy hoạch động. Để tách, mình sẽ duyệt qua từng số xem nó phải là số bắt đầu của một dãy cấp số cộng hay không.
Bài này của thím O(n) làm sao được. Tính TC/SC là phải tính theo worst case chứ.
Outer loop là O(n). Inner loop cũng là O(n). Phải là O(n^2) mới đúng
 
Bài này của thím O(n) làm sao được. Tính TC/SC là phải tính theo worst case chứ.
Outer loop là O(n). Inner loop cũng là O(n). Phải là O(n^2) mới đúng
Bác cần phải xem inner loop được trigger khi nào, tổng số iteration của tất cả các inner loop là bao nhiêu.
 
bác nhìn kỹ đi, có nested loop nhưng số lần visit qua từng phần tử là constant.
Ý tưởng là tách nums thành các dãy cấp số cộng dung sai k, rồi tính số beatiful subset từng dãy cấp số cộng bằng quy hoạch động. Để tách, mình sẽ duyệt qua từng số xem nó phải là số bắt đầu của một dãy cấp số cộng hay không.
ok, đọc lại hiểu rõ hơn rồi 💪
 
Backtrack :too_sad:
C#:
public class Solution {
    public bool IsBeautifulSubset(List<int> nums)
    {
        for(int i = 0; i<nums.Count-1; i++)
        {
            for(int j = i+1; j<nums.Count; j++)
            {
                if(Math.Abs(nums[i] - nums[j]) == p)
                {
                    return false;
                }
            }
        }
        return true;
    }

    public void CountBeautifulSubsets(int[] nums, List<int> temp, int index)
    {
        for(int i = index; i<nums.Length; i++)
        {
            temp.Add(nums[i]);
            if(IsBeautifulSubset(temp))
            {
                result++;
            }
            CountBeautifulSubsets(nums, temp, i+1);
            temp.RemoveAt(temp.Count - 1);
        }
    }

    public static int p = 0;
    public static int result = 0;

    public int BeautifulSubsets(int[] nums, int k) {
        p = k;
        result = 0;
        Array.Sort(nums);
        List<int> temp = new List<int>();
        CountBeautifulSubsets(nums, temp, 0);
        return result;
    }
}
 
bữa nay em mới luyện được bài two sum dùng hash table thì bao lâu mới đi phỏng vấn được vậy các bác, đang học song song cùng framework ạ :D
 
Python:
class Solution:
    def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
        capacity = defaultdict(int)
        totalPoint = 0
        for l in letters:
            capacity[l] += 1
            totalPoint += score[ord(l) - ord('a')]

        def validWord(word):
            freq = defaultdict(int)
            for char in word:
                freq[char] += 1
                if freq[char] > capacity[char]:
                    return False

            return True

        def calculatePoint():
            remaining = 0
            for key, value in capacity.items():
                remaining += score[ord(key) - ord('a')]*value

            return totalPoint - remaining

        n = len(words)
        ans = 0
        def backtrack(index):
            if index == n:
                nonlocal ans
                ans = max(ans, calculatePoint())
                return False

            if validWord(words[index]):
                for char in words[index]:
                    capacity[char] -= 1

                backtrack(index + 1)
                for char in words[index]:
                    capacity[char] += 1

            backtrack(index + 1)

        backtrack(0)
        return ans
 
Mình tính theo cái neetcode150 được ko fen, chứ 500 medium thấy xa quá, giờ gặp hard là sủi
Cứ luyện đi bác, để nó là thói quen là được rồi đừng bỏ, xác định học thì phải giỏi tới khi thành expert thì mới được quyền bỏ.
Thường hard cũng có dễ khó, mà thường hard thì sẽ học được nhiều thứ hay nên thấy hard ko làm đc thì nghiền ngẫm solution thôi bác.
Theo neetcode 150 mình đánh giá chỉ cho beginner thôi. Còn làm hết cái neetcode all thì may ra. Ngày xưa mình cũng kêu mong làm đc 3 400 bài là đc rồi, nay mở lại thấy đã làm 1k1 bài rồi :canny:
Càng về sau sẽ làm càng nhanh, 1 bài medium tốn tầm 15ph thôi, trên thì bật solution copy cho nhanh :sweat:


via theNEXTvoz for iPhone
 
Back
Top