我试图打印出给定数量的所有路径。但我的代码不能正常工作。我想我错过了打印所有可能组合的一些要点。例如;
你能帮我解决这些问题吗?
注意:最好是Java解决方案
XDocument doc = XDocument.Load(sourceDocument,LoadOptions.PreserveWhitespace);
foreach (XElement rootElement in doc.Root.Elements())
{
foreach (XElement childElement in rootElement.Descendants())
{
//add new body if <pos style=num>
if (childElement.Attribute("STYLE") != null)
{
//if next node is NUM
var nextNode = childElement.XPathSelectElement("following-sibling::*");
if (nextNode != null)
if (nextNode.Attribute("STYLE").Value == "NUM")
{
newBodyElem = new XElement("body");
}
}
}
答案 0 :(得分:0)
这可以使用回溯解决,但效率不高,下面是工作的java代码
/**
* Created by sumit sharma on 3/1/2016.
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class Main {
static int[] coinSet = {1,5,10,25};
static List<List<Integer>> possibleWays = new ArrayList<>();
static List<Integer> currentWay = new ArrayList<>();
public static void main(String[] args) {
List<Integer> countOfCoins = new ArrayList<>();
makeChange(7, 0, countOfCoins);
//System.out.print(possibleWays);
}
private static int makeChange(int amount, int startCoinIdx, List<Integer> coinsSoFar) {
if(startCoinIdx == coinSet.length){
if(amount == 0){
possibleWays.add(coinsSoFar);
System.out.println(coinsSoFar);
}
//System.out.println(coinsSoFar);
return 0;
}
for(int count = 0;(count*coinSet[startCoinIdx]) <= amount;count++){
List<Integer> temp = new ArrayList<>();
for(int i = 0;i < coinsSoFar.size();i++) temp.add(coinsSoFar.get(i));
for(int i = 0;i < count;i++) temp.add(coinSet[startCoinIdx]);
makeChange(amount - (count * coinSet[startCoinIdx]),startCoinIdx+1, temp);
temp.clear();
}
return 0;
}
}
指向Ideone上的解决方案:http://ideone.com/kIckmG