标签:style blog class code java color
好久没写动态规划,中午听到学长们讨论的一道题,就是给出一组硬币面额,和一个目标数值,求有几种找零方式(想半天没想清楚)
#include <iostream> #include <cstdlib> using namespace std; int count(int* s, int m, int n) { if (n == 0) return 1; if (n < 0 || m <= 0) return 0; return count(s, m - 1, n) + count(s, m, n-s[m-1]); } int main() { int arr[] = {1, 2, 3}; int m = sizeof(arr) / sizeof(int); cout<<count(arr, m, 4)<<endl; system("pause"); return 0; }
这是dfs暴力搜索
下面是未优化的dp代码
int count_dp(int *s, int m, int n) { int rows = m + 1; int cols = n + 1; int* dp = new int[rows * cols]; for (int i=0; i<cols; i++) dp[i] = 0; for (int i=0; i<rows; i++) dp[i * cols] = 1; for (int i=1; i<rows; i++) { int base = i * cols; for (int j=1; j<cols; j++) { int va = 0, vb = dp[base - cols + j]; if (j - s[i-1] >= 0) { va = dp[base + j - s[i-1]]; } dp[base + j] = va + vb; } } int ret = dp[cols * rows - 1]; delete[] dp; return ret; }
感觉这类问题在分解为最优子问题时总是划分为某个元素取与不取,还是没什么长进
参考:
http://www.acmerblog.com/dp6-coin-change-4973.html
标签:style blog class code java color
原文地址:http://www.cnblogs.com/lailailai/p/3717946.html