-
Notifications
You must be signed in to change notification settings - Fork 0
【Day 70 】2023-08-18 - 932. 漂亮数组 #72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
|
思路问题分解为子问题,递归解决,注意需要分为奇数和偶数 代码class Solution:
def beautifulArray(self, N: int) -> List[int]:
@lru_cache(None)
def dp(n):#递归调用
if n==1:
return [1]
ans=[]
for i in dp(n-n//2):
ans+=[i*2-1]
for j in dp(n//2):
ans+=[j*2]
return ans
return dp(N) 复杂度分析
|
class Solution:
def beautifulArray(self, N):
if N == 1:
return [1]
odds = self.beautifulArray((N + 1) // 2)
evens = self.beautifulArray(N // 2)
return [2*x - 1 for x in odds] + [2*x for x in evens]
solution = Solution()
N = 4
beautiful_array = solution.beautifulArray(N)
print(beautiful_array) |
|
代码class Solution {
Map<Integer, int[]> memo;
public int[] beautifulArray(int n) {
memo = new HashMap();
return f(n);
}
public int[] f(int n){
if(memo.containsKey(n)){
return memo.get(n);
}
int[] ans = new int[n];
if(n == 1){
ans[0] = 1;
} else {
int t = 0;
for(int x: f((n+1)/2)){
ans[t++] = 2*x-1;
}
for(int x:f(n/2)){
ans[t++] = 2*x;
}
}
memo.put(n, ans);
return ans;
}
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
932. 漂亮数组
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/beautiful-array/
前置知识
题目描述
The text was updated successfully, but these errors were encountered: