樓上走到樓下共有10個台階,每一步有3種走法:走1個台階;走2個台階;走3個台階.問可走多少種方案?
分析
這個題用排列組合不好作,無法確定步驟,我提供一種方法,供大家參考借鑒:
不妨設有n階台階,既然一次只能走一步或2步或3步,那么假設現在僅剩下最后一步要走,
有三種情況:
一 只需要走一步,這時已經走了(n-1)階,走法與走n-1階相同,有f(n-1)階走法;
二 只需要走兩步,同上分析有f(n-2);
三 只需要走三步,有f(n-3);
所以走n階台階有f(n)=f(n-1)+f(n-2)+f(n-3)種走法;
很明顯,走1階台階有1種方法;
走2階有兩種走法;
走3階有4種走法,如下:1 1 1 1 2 2 1 3;
所以我列出總台階數與走法的對應表:
1 2 3 4 5 6 7 8 9 10
1 2 4 7 13 24 44 81 149 274
所以有274種走法,是不是不可思議啊
C語言寫法
if(n==1) return 1; else if(n==2) return 2; else if(n==3) return 4; else return f(n-1)+f(n-2)+f(n-3);
我的寫法一
static void Main(string[] args) { int x = run(10); Console.WriteLine(x); Console.ReadKey(); } static int run(int x) { if (x == 1) { return 1; } else if (x == 2) { return 2; } else if (x == 3) { return 4; } else { return run(x - 1) + run(x - 2) + run(x - 3); } }
我的寫法二
static void Main(string[] args) { List<int> list = new List<int>() { 1, 2, 4 }; for (int i = 3; i < 10; i++) { int count = list.Sum(); list.RemoveAt(0);//刪除第一個 list.Add(count);//增加相加的和 Console.WriteLine(list[2]); } Console.ReadKey(); }
我的寫法三
static void Main(string[] args) { int[] count = new int[] { 1, 2, 4 }; for (int i = 4; i < 11; i++) { int sum = count.Sum();//求和 count[(i - 1) % 3] = sum;//取3的摸 Console.WriteLine(sum); } Console.ReadKey(); }
請問下各位高手有沒有更優化的寫法,一起探討學習交流下。。。覺得還是挺有意思的題目。
第三種方案可能是最優的寫法了,但很多人可能一下子想不到。。。