解法一:暴力搜索,逐步递归
1 class Exchange { 2 public: 3 int countWays(vector<int> penny, int n, int aim) { 4 // write code here 5 if (n == 0 || aim < 0) 6 return 0; 7 return process(penny,0,aim); 8 } 9 int process(vector<int> array, int index, int aim) 10 { 11 int res = 0; 12 if (index == array.size()) 13 res = aim == 0 ? 1 : 0; 14 else 15 { 16 for (int i = 0; array[index] * i <= aim; i++) 17 { 18 res += process(array, index + 1, aim - array[index] * i); 19 } 20 } 21 return res; 22 } 23 };
解法二:记忆搜索
本质上也是动态规划,一定程度上简化了计算
动态规划知识点:
其他解答参考: