如果我有一個數字串列,
例如 [3,4,5,7,0,5,2] 。
串列中的每個元素都代表我可以從這個單元格向前移動的最大步數。一個好的串列是當我可以到達串列的末尾時,一個壞的串列是當我沒有足夠的步驟到達串列的末尾時。
我嘗試撰寫以下代碼,但不正確:
def recu(li):
if li[0] == 0:
print("not working")
return 'Null'
if li[0] >= len(li):
print('finished with success')
return 'Null'
if li[0] < len(li):
print(li[li[0]:])
return recu(li[li[0]:])
recu(list1)
你能幫我么 ?
uj5u.com熱心網友回復:
這是您正在尋找的邏輯嗎?
def is_good(l):
e = l[0]
return False if e == 0 else True if e >= len(l) -1 else is_good(l[e:])
我嘗試了一些串列 - 從我對問題的理解來看,這是有道理的:
is_good([0,1,3]) # Returns False
is_good([3,3,5,0,1]) # Returns False
is_good([1,7,2,3,0]) # Returns True
is_good([[3,4,5,7,0,5,2]) # Returns True
我假設你必須踩到或超越最后一個元素 - 如果你只需要超越
def is_good(l):
e = l[0]
return False if e == 0 else True if e >= len(l) else is_good(l[e:])
uj5u.com熱心網友回復:
您可以為此使用動態編程。
def solution(x):
a = [False] * len(x) # list of accessible cells
a[0] = True # first cell accessible
for i, (p, k) in enumerate(zip(a, x)):
if p:
for j in range(i, i k 1):
try:
a[j] = True # mark all the cells that can be reached from the processed to the cells
except IndexError:
return True
return False
print(solution([3,4,5,7,0,5,2]))
您還可以使用遞回:
arr = [3, 4, 5, 7, 0, 5, 2]
def f(i):
if i arr[i] >= len(arr):
print(True)
exit(0)
for j in range(i 1, i arr[i] 1):
f(j)
f(0)
print(False)
uj5u.com熱心網友回復:
我可以提供您的問題的解決方案,使用演算法深度優先搜索。
#include <iostream>
#include <vector>
using namespace std;
const int maximumSize=40;
vector<int> visited(maximumSize, 0);
void dfs(int current, int previous, vector<int>& input)
{
if(visited[current]==1)
{
return;
}
if(current>=(input.size()-1))
{
cout<<"finished with success"<<endl;
return;
}
if((input[current]==0) && (current<(input.size()-1)))
{
cout<<"not working"<<endl;
return;
}
visited[current]=1;
int newCurrent=(current input[current]);
for(int next=newCurrent; next<=newCurrent; next)
{
if(next==previous)
{
continue;
}
dfs(next, current, input);
}
return;
}
void solve()
{
vector<int> inputVector={3, 4, 5, 7, 0, 5, 2};
dfs(0, -1, inputVector);
return;
}
int main()
{
solve();
return 0;
}
輸入:
{3, 4, 5, 7, 0, 5, 2}
結果如下:
finished with success
輸入:
{3, 4, 5, 0, 7, 0, 5}
結果如下:
not working
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371655.html
上一篇:如何將2個方法回圈在一起?
