这类问题一般是给出候选集合(一般为数组 array [ ])和一个限定值(S),然后让你求某一结果。
一般DFS与DP均可。下面谈谈这两种思维方式不同。
DFS一般是对数组array元素进行讨论,比如最后一个元素的有无。然后顺序递归,削减数组长度,通过递归遍历整个数组,得出最终结果。
比如全排列问题,比如组合问题。
DP则直接对限定值S进行讨论,比如S-array[n] 的值是什么。通过讨论S的前一值,建立DP表格,削减S,通过保存S的前一值来降低复杂度,得出最终结果。
比如背包问题,比如换硬币问题。
下面通过换硬币问题的两种解法,来具体展示一下思维着力点的不同。
问题描述(LeetCode):
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1
.
Example 1:
coins = [1, 2, 5]
, amount = 11
return 3
(11 = 5 + 5 + 1)
Example 2:
coins = [2]
, amount = 3
return -1
.
Note:
You may assume that you have an infinite number of each kind of coin.
DFS解法:对是否包含coins[n-1]进行讨论,然后递归值conis[n-2],直至conis[0]。
public class Solution { private int minNum = 0x7fffffff; public void coinNum(int[] coins, int amount, int end, int num){ if (end < 0){ return; } if (amount == 0){ if (num < minNum){ minNum = num; } }else { if(num > minNum) return; // 大于最小次数,不再递归。 for(int i = end; i > -1; i--){ if(amount >= coins[i]){ coinNum(coins, amount - coins[i], i, num+1); //包含coins[i]的情况 } } } } public int coinChange(int[] coins, int amount) { coinNum(coins, amount, coins.length-1, 0); if (minNum == 0x7fffffff){ return -1; }else return minNum; } }
DP解法,主要对amount进行讨论,通过递归算出amount-coin 的值来的出最终结果。
public class Solution { private int coinNum(int[] coins, int amount, int[] result){ if (amount < 0) return -1; if (amount == 0) return 0; if (result[amount-1] != 0) return result[amount-1]; int min = 0x7fffffff; for (int coin : coins){ int tmp = coinNum(coins, amount-coin, result); if (tmp >= 0 && tmp < min){ min = tmp+1; } } result[amount-1] = (min == 0x7fffffff) ? -1 : min; return result[amount-1]; } public int coinChange(int[] coins, int amount) { return coinNum(coins, amount, new int[amount]); } }