前几天做了挺多的回溯的题,我就用回溯的方法做了这道题,结果提交的时候超出内存限制了。(我在最底下粘贴出了官方的一种官方答案。)
回溯:
import java.util.ArrayList;
import java.util.List;
class stairs{
public int climbStairs(int n) {
return permutation(n).size();
}
public List<List<Integer>> permutation(int n){
List<List<Integer>> res = new ArrayList<>();
if(n==0) return res;
List<Integer> path = new ArrayList<>();
int nums[] = new int[] {1,2};
dfs(nums,n,0,path,res);
return res;
}
public void dfs(int nums[],int sum,int depth,List<Integer> path,List<List<Integer>> res) {
if(depth>sum) {
return;
}
if(depth==sum) {
res.add(new ArrayList<>(path));
return;
}
for(int i=0;i<2;i++) {
depth = depth+nums[i];
path.add(nums[i]);
dfs(nums,sum,depth,path,res);
path.remove(path.size()-1);
depth = depth-nums[i];
}
}
}
public class ClimbingStairs {
public static void main(String args[]) {
stairs hah = new stairs();
System.out.println(hah.permutation(4));
System.out.println(hah.climbStairs(4));
}
}
测试结果:
[[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2]]
5
官方答案:
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
官方用了一种规律:
f(x)=f(x−1)+f(x−2)
f(0)=1
f(1) = 1
f(2) = 2,f(3) = 3,f(4) = 5,……
class Solution {
public int climbStairs(int n) {
int p = 0, q = 0, r = 1;
for (int i = 1; i <= n; ++i) {
p = q;
q = r;
r = p + q;
}
return r;
}
}